简体   繁体   中英

Typescript: How to set values of in an array of objects from another array

Let's say I have two arrays...

array1 = [{'age':'', 'name':'John'}, {'age':'', 'name':'Mark'}, {'age':'', 'name':'Curtis'}]


array2 = ['23','25','29']

I know I can use a nested for loop to set the 'age' object to the values in array2. But is there another way with one of the javascript methods like find or map? So the desired outcome would be...

array3 = [{'age':'23', 'name':'John'}, {'age':'25', 'name':'Mark'}, {'age':'29', 'name':'Curtis'}]

Also what is array2 was...

array2 = [{'value':'23'},{'value':'25'},{'value':'29'}]

Could I do the same thing even if the objects have different names? Thanks.

Use Array.map() and take the age from the 1st array using the index ( i ), and combine using object destructuring:

 const array1 = [{'age':'', 'name':'John'}, {'age':'', 'name':'Mark'}, {'age':'', 'name':'Curtis'}] const array2 = ['23','25','29'] const result = array1.map((o, i) => ({...o, age: array2[i] })) console.log(result)

Handle the 2nd version of array2 is similar, use the index, and take the value:

 const array1 = [{'age':'', 'name':'John'}, {'age':'', 'name':'Mark'}, {'age':'', 'name':'Curtis'}] array2 = [{'value':'23'},{'value':'25'},{'value':'29'}] const result = array1.map((o, i) => ({...o, age: array2[i].value })) console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM