我有这个对象数组:
0:key:"name" value:"John"
1:key:"age" value:"30"
2:key:"car" value:"Ford"
我怎么把它变成这样:
[{ "name":"John", "age":30, "car":"ford" }]
我正在尝试这样的事情:
tempArray.forEach(function(s) {
var object = {
s.key: s.value
}
newArray.push(object);
});
答案 0 :(得分:1)
您可以使用Array.reduce()
var arr = [{key:"name", value:"John"},
{key:"age", value:"30"},
{key:"car" ,value:"Ford"}];
var result = [];
var map = arr.reduce((a,curr)=>{
a[curr.key] = curr.value;
return a;
},{});
result.push(map);
console.log(result);
答案 1 :(得分:1)
我希望它将对您有帮助
var a = [{name:"a"},{age:10},{car:"ford"}];
var d={};
a.map((data)=>{
if(data.name){
d.name=data.name;
}else if(data.age){
d.age=data.age
}else{
d.car=data.car
}
})
console.log(d)
答案 2 :(得分:0)
您可以将Array#map
用于单个键/值对,并使用Object.assign
将所有内容合并到一个对象中
var array = [{ key: "name", value: "John" }, { key: "age", value: "30" }, { key: "car", value: "Ford"}],
object = Object.assign(...array.map(({ key, value }) => ({ [key]: value })));
console.log(object);
答案 3 :(得分:0)
let array = [{ key: "name", value: "John" }, { key: "age", value: "30" }, { key: "car", value: "Ford"}];
let answer = [array.reduce((acc, cur) => {
acc[cur.key] = cur.value
return acc
},{})]
console.log(answer)
您可以使用reduce遍历数组并快速创建它们