问题
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"}
]
回答1:
Using Array.prototype.slice(), Array.prototype.map() and 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));
回答2:
Hope this helps
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);
来源:https://stackoverflow.com/questions/42895449/how-to-convert-array-of-arrays-to-array-of-objects-where-keys-are-taken-from-the