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

筅森魡賤 提交于 2021-01-18 05:58:47

问题


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?


回答1:


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



回答2:


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

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

You can loop like this.




回答3:


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)



回答4:


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


来源:https://stackoverflow.com/questions/53923317/javascript-pushing-new-property-to-objects-that-are-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!