Test name | Executions per second |
---|---|
one liner | 45847.1 Ops/sec |
reduced | 297678.1 Ops/sec |
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 = (arr, keyField) =>
Object.assign({}, arr.map(item => ({[item[keyField]]: item})))
const peopleObject = arrayToObject(peopleArray, "id")
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")