NodeJS 如何将数组数据转换为对象[已关闭]

chhqkbe1  于 2023-04-05  发布在  Node.js
关注(0)|答案(2)|浏览(227)

已关闭,此问题需要更focused,目前不接受回答。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

3天前关闭。
Improve this question
我有一个数据数组,但我想将其转换为对象

如何将数据数组变成这样对象?

[
{
date: "2018-01-31",
icp: "65.59",
slc: "65.83",
dc: "64.55"
},
{
date: "2018-02-28",
icp: "61.61",
slc: "62.31",
dc: "59.93"
},
{
...
}
]

请帮我解决这个问题

ar7v8xwq

ar7v8xwq1#

只需使用forEach并执行一些switch逻辑,如下所示:

const arr = ['2018-01-31','65.59','65.83','64.55','2018-02-28','61.61','62.31','59.93'];
let newArr = [];
let obj;
arr.forEach((data, index)=>{
  switch(index % 4) {
    case 0:
      obj = {date: data};
      break;
    case 1:
      obj.icp = data;
      break;
    case 2:
      obj.slc = data;
      break;
    default:
      obj.dc = data;
      newArr.push(obj);
  }
});
console.log(newArr);
nlejzf6q

nlejzf6q2#

使用以下代码尝试一次:

const arr = [
  "2018-01-31",
  "65.56",
  "65.83",
  "64.55",
  "2018-02-28",
  "61.61",
  "62.31",
  "59.93",
  "2018-03-31",
  "61.87",
  "62.85",
  "60.26",
  "2018-04-30",
  "67.43",
  "68.39",
  "65.86",
];

const result = [];
for (let i = 0; i < arr.length; i += 4) {
  const date = arr[i];
  const icp = arr[i + 1];
  const slc = arr[i + 2];
  const dc = arr[i + 3];
  result.push({ date, icp, slc, dc });
}

console.log(result);

相关问题