json 如何从数组的每个元素中提取特定的值并将其转换为对象数组?

hc2pp10m  于 2023-02-01  发布在  其他
关注(0)|答案(3)|浏览(130)

我想从下面数组的每个元素中提取名称和费率,并将它们转换为对象数组

[
  'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
  'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
  'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
]

以下是我期望得到的:

[
{"name":BTCUSDT, "rate":0.01%},
{"name":ETHUSDT,"rate":0.01%},
{"name":BCHUSDT,"rate":0.01%},
]

感谢您的任何建议。

olmpazwi

olmpazwi1#

const arr = [
  'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
  'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
  'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
];
var data = [];
const result = arr.reduce((data, value) => {
  const splitArray = value.split(' ');
  var params = {
    name: splitArray[0],
    rate: splitArray[1].split('\t')[4]
  }
  data.push(params);
  return data;
}, [])

const output = result;
console.log(output);
ymdaylpp

ymdaylpp2#

尝试使用arr.reduce()

const arr = [
  'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
  'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
  'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
];

const res = arr.reduce((acc, item) => {
  debugger;
  const splitArr = item.split(' ');
  acc.push({
    [splitArr[0]]: splitArr[1].split('\t')[4]
  });
  return acc;
}, [])

console.log(res)
5rgfhyps

5rgfhyps3#

可以结合使用数组Map和字符串拆分来实现此目的:

const arr = [
  'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
  'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
  'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
];

const result = arr.map(item => {
  const elements = item.split('\t');
  const name = elements[0].split(" ")[0];
  return {
    name,
    rate: elements[4]
  };
});

console.log(result);

相关问题