I have an array like this:
var arr = [
["1", "tony stark"],
["2", "steve rogers"],
["3", "thor"],
["4", "nick fury"]
];
I want the values from the array to be written to a object like this
var obj = [
{id:"1", name:"tony stark"},
{id:"2", name:"steve rogers"},
{id:"3", name:"thor"},
{id:"4", name:"nick fury"}
];
答案 0 :(得分:3)
您可以分解数组并使用short hand properties构建一个新对象。
var array = [["1", "tony stark"], ["2", "steve rogers"], ["3", "thor"], ["4", "nick fury"]],
result = array.map(([id, name]) => ({ id, name }));
console.log(result);
答案 1 :(得分:2)
您可以映射到数组并创建对象
const arr = [
["1", "tony stark"],
["2", "steve rogers"],
["3", "thor"],
["4", "nick fury"]
];
var obj = arr.map((info) => {
return {
id: info[0],
name: info[1]
};
})
console.log(obj)