Answers for "converting-an-array-of-objects-to-a-map"

1

converting-an-array-of-objects-to-a-map

const peopleArray = [
  { id: 123, name: "dave", age: 23 },
  { id: 456, name: "chris", age: 23 },
  { id: 789, name: "bob", age: 23 },
  { id: 101, name: "tom", age: 23 },
  { id: 102, name: "tim", age: 23 }
]

const arrayToObject = (array, keyField) =>
   array.reduce((obj, item) => {
     obj[item[keyField]] = item
     return obj
   }, {})

const peopleObject = arrayToObject(peopleArray, "id")

console.log(peopleObject[idToSelect])

const peopleObject = {
  "123": { id: 123, name: "dave", age: 23 },
  "456": { id: 456, name: "chris", age: 23 },
  "789": { id: 789, name: "bob", age: 23 },
  "101": { id: 101, name: "tom", age: 23 },
  "102": { id: 102, name: "tim", age: 23 }
}
Posted by: Guest on July-16-2021

Code answers related to "converting-an-array-of-objects-to-a-map"

Code answers related to "Javascript"

Browse Popular Code Answers by Language