假设我们有以下对象数组-
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 ] ]