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?
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?
Share Improve this question edited Dec 25, 2018 at 14:53 michaelbane asked Dec 25, 2018 at 14:41 michaelbanemichaelbane 1191 silver badge8 bronze badges4 Answers
Reset to default 11You 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 });
You can set the property directly by assigning value To it like this
Person[0].age = oldest[0]:
You can loop like this.
You can use array.forEach, which will iterate through the same array and you can create a new property to the same array.
If you want get a new array you can use array.map, which will create a new array.
I hope this will solve the issue.
const person = [
{ first: 'firstName', last: 'lastName', year: 1439, passed: 1489 },
{ first: 'secondName', last: 'lastName', year: 1499, passed: 1590 },
{ first: 'thirdName', last: 'lastName', year: 1539, passed: 1570 },
{ first: 'fourthName', last: 'lastName', year: 1993, passed: 2018 },
]
person.forEach(obj => obj["age"] = obj.passed - obj.year)
console.log("same array with added age property", person)
Since both arrays person
and oldest
have the same length, you can just iterate over either, construct new objects with age
properties from the elements of both arrays at the same index and push them to a result array.
const person = [
{ first: 'firstName', last: 'lastName', year: 1439, passed: 1495 }
];
const oldest = person.map(x => x.passed - x.year);
const result = [];
person.forEach(({first, last, year, passed}, i) => result.push({first, last, year, passed, age: oldest[i]}));
console.log(result);
Given a zip
function (which unfortunately is not yet standard JavaScript), you could also shorten this to:
zip(person, oldest).map(([{first last, year, passed}, age]) => ({first, last, year, passed, age}));