在 JavaScript 中将对象数组转换为数组数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 14:36:17

假设,我们有以下对象数组 −

const arr = [
   {"2015":11259750.05},
   {"2016":14129456.9}
];

我们需要编写一个 JavaScript 函数来接收一个这样的数组。该函数应根据输入数组准备一个数组数组。

因此,上述数组的输出应如下所示−

const output = [
   [2015,11259750.05],
   [2016,14129456.9]
];

示例

其代码为 −

const arr = [
   {"2015":11259750.05},
   {"2016":14129456.9}
];
const mapToArray = (arr = []) => {
   const res = [];
   arr.forEach(function(obj,index){
      const key= Object.keys(obj)[0];
      const value = parseInt(key, 10);
      res.push([value, obj[key]]);
   });
   return res;
};
console.log(mapToArray(arr));

输出

控制台中的输出将是 −

[ [ 2015, 11259750.05 ], [ 2016, 14129456.9 ] ]

相关文章


有用资源