Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - pushing new property to objects that are in an array

I got an array person containing many objects that look like this:

const person = [
{ first: 'firstName', last: 'lastName', year: 1439, passed: 1495 },
 ...
]

I have counted how many years the person lived:

const oldest = person.map(x => x.passed - x.year);

Got new array with the years for every person.

Now I would like to push this calculated year as a new property age to each person object in this array.

Can you help me out?

like image 229
Peter Hrnčírik Avatar asked Dec 25 '18 14:12

Peter Hrnčírik


1 Answers

You could add a new property

person.forEach(p => p.lifetime = p.passed - p.year);

Or map a new array of objects

persons = person.map(p => ({ ...p, lifetime: p.passed - p.year });
like image 161
Nina Scholz Avatar answered Oct 28 '22 06:10

Nina Scholz