I’ve got this code:
const arr = [{name: 'fred', age: 20}, {name: 'john', age: 50}]
const result = arr.reduce((acc, item) => {
acc[item.name] = item.age
return acc
}, {})
console.log(result)
How do I make the following 2 lines into 1 line?
acc[item.name] = item.age
return acc
>Solution :
Use the spread syntax (...) to combine item with your new key/value, then use ({}) to directly return the object:
You could also use the destructing assignment to get name and age as separate variable in stead of item, see commented line for an example.
const arr = [{name: 'fred', age: 20}, {name: 'john', age: 50}]
const result = arr.reduce((acc, item) => ({ ...acc, [item.name]: item.age }), {})
// Or with a destructuring assignment
// arr.reduce((acc, { name, age }) => ({ ...acc, [name]: age }), {})
console.log(result)