假设我有一个像这样的数组:
[
{
field: "firstname",
value: "John"
},
{
field: "lastname",
value: "Doe"
},
{
field: "hobbies",
value: "singing, basketball"
},
]
现在我想将其转换为这样的对象,其中上述数组中的键是field
,值是value
:
const result = {
firstname: "John",
lastname: "Doe",
hobbies: "Singing, basketball"
}
答案 0 :(得分:2)
您可以像这样使用Array.prototype.reduce:
const arr = [
{
field: "firstname",
value: "John"
},
{
field: "lastname",
value: "Doe"
}
];
const obj = arr.reduce((acc, val) => {
acc[val.field] = val.value;
return acc;
}, {});
这将使用值和字段填充obj
对象。
答案 1 :(得分:2)
您可以使用.reduce()
方法来获得所需的输出:
const data = [
{field: "firstname", value: "John"},
{field: "lastname", value: "Doe"}
];
const result = data.reduce((r, {field: key, value}) => (r[key] = value, r), {});
console.log(result);
答案 2 :(得分:1)
您可以通过应用简单的for
循环来实现...
const arr=[
{
field: "firstname",
value: "John"
},
{
field: "lastname",
value: "Doe"
}
];
const obj={} //declare an object
for(let i=0;i<arr.length;i++){
obj[arr[i].field]=arr[i].value;
}
alert(obj) //output : {firstname: "John", lastname: "Doe" }
答案 3 :(得分:1)
map()
到Object.values
的数组并将其传递到Object.fromEntries()
const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ]
const res = Object.fromEntries(arr.map(Object.values))
console.log(res)
另一个解决方案可能是使用reduce()
const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ]
const res = arr.reduce((ac,a) => (ac[a.field] = a.value,ac),{})
console.log(res)