How to convert an array into an object in javascript with mapped key-value pairs?

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)

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)

Leave a Comment