我有一个返回数组数组的变量,每个数组中的每个项都用双引号。
var arrayOfArrays = [
[ "Name", "Age", "Address" ],
[ "A", "43", "CA" ],
[ "B", "23", "VA" ],
[ "C", "24", "NY" ]
]
我需要将其转换为以下内容:
var arrayOfObjects = [
{"Name":"A", "Age":"43", "Address":"CA"},
{"Name":"B", "Age":"23", "Address":"VA"},
{"Name":"C", "Age":"24", "Address":"NY"}
]
答案 0 :(得分:4)
使用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));
答案 1 :(得分:0)
希望这有帮助
var arrayOfArrays = [
[ "Name", "Age", "Address" ],
[ "A", "43", "CA" ],
[ "B", "23", "VA" ],
[ "C", "24", "NY" ]
]
var arrayOfObjects = [];
function changeToObject(arrayOfArrays){
for (var i = 1; i < arrayOfArrays.length; i++) {
var json = {
"Name" : "",
"Age" : "",
"Address" : ""
}
json.Name = arrayOfArrays[i][0];
json.Age = arrayOfArrays[i][1];
json.Address = arrayOfArrays[i][2];
arrayOfObjects.push(json);
};
console.log(arrayOfObjects)
}
changeToObject(arrayOfArrays);