对象数组到 JavaScript 中的数组数组


假设我们有一个像这样的对象数组 −

const arr = [
   {"Date":"2014","Amount1":90,"Amount2":800},
   {"Date":"2015","Amount1":110,"Amount2":300},
   {"Date":"2016","Amount1":3000,"Amount2":500}
];

我们需要编写一个 JavaScript 函数,其中包含一个这样的数组,并将此数组映射到另一个数组,该数组包含数组而不是对象。

因此,最终数组将如下所示 −

const output = [
   ['2014', 90, 800],
   ['2015', 110, 300],
   ['2016', 3000, 500]
];

示例

它的代码如下 −

const arr = [
   {"Date":"2014","Amount1":90,"Amount2":800},
   {"Date":"2015","Amount1":110,"Amount2":300},
   {"Date":"2016","Amount1":3000,"Amount2":500}
];
const arrify = (arr = []) => {
   const res = [];
   const { length: l } = arr;
   for(let i = 0; i < l; i++){
      const obj = arr[i];
      const subArr = Object.values(obj);
      res.push(subArr);
   };
   return res;
};
console.log(arrify(arr));

输出

控制台中的输出如下 −

[ [ '2014', 90, 800 ], [ '2015', 110, 300 ], [ '2016', 3000, 500 ] ]

更新日期:2020 年 11 月 23 日

780 次观看

提升你的职业

通过完成课程获取认证

开始
广告
© . All rights reserved.