Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you set object prop and return object in one line?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading