如何在具有映射键值对的javascript中将数组转换为对象? [英] How to convert an array into an object in javascript with mapped key-value pairs?
本文介绍了如何在具有映射键值对的javascript中将数组转换为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个像这样的数组:
Let's say I have an array like so:
[
{
field: "firstname",
value: "John"
},
{
field: "lastname",
value: "Doe"
},
{
field: "hobbies",
value: "singing, basketball"
},
]
现在,我想将其转换为一个对象,如下所示,其中键是 field
,值是上述数组中的 value
:
Now I want to convert it into an object like so where in the key is the field
and the value is the value
from the above array:
const result = {
firstname: "John",
lastname: "Doe",
hobbies: "Singing, basketball"
}
推荐答案
map()
将数组转换为 Object.values
并将其传递给
map()
the array to Object.values
and pass it to 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()
The another solution could be using 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)
这篇关于如何在具有映射键值对的javascript中将数组转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文