[英]Typescript: How to set values of in an array of objects from another array
Let's say I have two arrays...假设我有两个 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.我知道我可以使用嵌套的 for 循环将“年龄”object 设置为 array2 中的值。 But is there another way with one of the javascript methods like find or map?但是还有另一种方法可以使用 javascript 方法之一,例如 find 或 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...
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:使用Array.map()
并使用索引( i
)从第一个数组中获取age
,并使用 object 解构组合:
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:处理2nd版本的array2
类似,使用索引,取值:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.