假设我有一个像这样的数组:
[
{
field: "firstname",
value: "John"
},
{
field: "lastname",
value: "Doe"
},
{
field: "hobbies",
value: "singing, basketball"
},
]
现在我想将它转换成一个对象,就像键中的位置一样field
其值为value
从上面的数组:
const result = {
firstname: "John",
lastname: "Doe",
hobbies: "Singing, basketball"
}
map()
数组到Object.values
并将其传递给Object.fromEntries() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)