7

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?

4 Answers 4

11

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 });
Sign up to request clarification or add additional context in comments.

Comments

0

You can set the property directly by assigning value To it like this

Person[0].age = oldest[0]:

You can loop like this.

Comments

0

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)

Comments

0

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}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.