如何在javascript中将数组转换为具有映射键值对的对象?

2024-01-11

假设我有一个像这样的数组:

[ 
  {
    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(使用前将#替换为@)

如何在javascript中将数组转换为具有映射键值对的对象? 的相关文章

随机推荐