How to build a new list of objects, each with a new property, given an initial list of objects in ES6 without loops?

mrj Source

If I have a list of objects, eg:

const poeple = [
    {name: "Johhny", born:1980, passed:2080},
    {name: "Jenny", born:1990, passed:2093},
    ...{name: "Jan", born:1999, passed:2096}
    ];

I found out how to make a new list, with the ages like this:

const ages = people.map(person => person.passed - person.born);

And I can add the property 'age' to the original people, like this:

people.map(person => person.age - person.born);

But, is there a (quick/efficient/eloquent) way to just make a new array, with each object having the additional property, as I don't want to change the original array?

I tried to use the array push method, but that just adds objects one at a time, with a loop, is there any other way to do this with less code?

javascriptarraysperformanceecmascript-6arrow-functions

Answers

answered 6 days ago Nenad Vracar #1

You can use map method with spread syntax in object.

const people = [{name: "Johhny", born:1980, passed:2080},{name: "Jenny", born:1990, passed:2093},{name: "Jan", born:1999, passed:2096}];
	
const result = people.map(person => ({
  ...person,
  age: person.passed - person.born
}))

console.log(result)

answered 6 days ago Ori Drori #2

You can use Array.map() and create the new object by appending the age to the existing object using Object.assign():

const people = [{name: "Johhny", born:1980, passed:2080},{name: "Jenny", born:1990, passed:2093},{name: "Jan", born:1999, passed:2096}];

const result = people.map(o => Object.assign({
  age: o.passed - o.born
}, o));

console.log(result);

comments powered by Disqus