简体   繁体   English

Typescript:如何在另一个数组的对象数组中设置值

[英]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.

相关问题 如何将类型4中的值从一个对象数组复制到另一个对象数组中? - How to copy values from one array of objects to another array of objects in typescript, angular 4? 如何从一个对象数组中获取值到另一个对象数组中 - How to get values from one array of objects into another array of objects 如何从对象数组中的值数组创建新的对象数组。 TypeScript? - How to create a new array of objects from an array of values in an array of objects. TypeScript? 如何在 TypeScript 中的对象数组中将数据从一个对象数组获取到另一个对象数组中 - How to Get Data From One Array of Objects into another in Array of Objects in TypeScript 从另一组对象数组中将属性添加到另一个对象数组 - Adding Property to another Array of objects from another set of Array of Objects 如何从Javascript中的另一个数组中删除数组的项目值集 - How to remove set of item values of array from another array in Javascript 如何使用另一个对象数组的键和 arrays 数组中的值来构造对象数组? - How to construct an array of objects by using the keys of another array of objects and values from the array of arrays? 从 JavaScript 中的另一个对象数组替换一个对象数组的值 - Replace values of an array of objects from another array of objects in JavaScript 从嵌套在另一个对象数组中的对象数组中访问值 - accessing values from an array of objects nested within another array of objects 根据来自另一个对象数组的多个值过滤对象数组 - Filter array of objects based on multiple values from another array of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM