如何将数组数组转换为从第一个数组获取键的对象数组? [英] How to convert array of arrays to array of objects where keys are taken from the first array?
本文介绍了如何将数组数组转换为从第一个数组获取键的对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个变量,它返回一个数组数组,每个数组中的每个项目都用双引号引起来。
I have a variable that is returning an array of arrays, with each item in each array in double quotes.
var arrayOfArrays = [
[ "Name", "Age", "Address" ],
[ "A", "43", "CA" ],
[ "B", "23", "VA" ],
[ "C", "24", "NY" ]
]
我需要将其转换为以下内容:
I need to convert this to the following:
var arrayOfObjects = [
{"Name":"A", "Age":"43", "Address":"CA"},
{"Name":"B", "Age":"23", "Address":"VA"},
{"Name":"C", "Age":"24", "Address":"NY"}
]
推荐答案
使用 Array.prototype.slice()
, Array.prototype.map()
和 Array.prototype.forEach()
:
let arrays = [
["Name", "Age", "Address"],
["A", "43", "CA"],
["B", "23", "VA"],
["C", "24", "NY"]
];
let keys = arrays[0];
let values = arrays.slice(1);
let objects = values.map(array => {
let object = {};
keys.forEach((key, i) => object[key] = array[i]);
return object;
});
console.log(JSON.stringify(objects));
这篇关于如何将数组数组转换为从第一个数组获取键的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文