[英]How to merge objects from two different arrays of same length?
I am working in vanilla JavaScript.我正在使用香草 JavaScript。 I have two arrays of the same length.
我有两个长度相同的数组。 Each of them is containing objects.
它们中的每一个都包含对象。 I need to create one array with objects combined.
我需要创建一个组合了对象的数组。 How?
如何?
So, in code, my input is:所以,在代码中,我的输入是:
const arr1 = [{name: "John"}, {name: "Peter"}];
const arr2 = [{age: 56}, {age: 22}]
Desirable output:期望输出:
const arr3 = [{name: "John", age: 56}, {name: "Peter", age: 22}]
I saw solution that ES6 offers, and it goes like this:我看到了 ES6 提供的解决方案,它是这样的:
const object1 = {
name: 'John'
}
const object2 = {
age: 56
}
const object3 = {...object1, ...object2 }
That works just great!这很好用! I would like to implement this same solution in this example whit objects in arrays using this spread operator.
我想在此示例中使用此扩展运算符在数组中的 whit 对象中实现相同的解决方案。 How?
如何? :)
:)
Thank you.谢谢你。
Using Array.prototype.map()
and spread syntax:使用
Array.prototype.map()
和传播语法:
const arr1 = [{ name: 'John' }, { name: 'Peter' }]; const arr2 = [{ age: 56 }, { age: 22 }]; const arr3 = arr1.map((v, i) => ({ ...v, ...arr2[i] })); console.log(arr3);
Another option另外一个选项
const arr1 = [{name: "John"}, {name: "Peter"}]; const arr2 = [{age: 56}, {age: 22}]; const result = []; for(let i = 0; i < arr1.length; i++) result.push(Object.assign(arr1[i], arr2[i])); console.log(result)
PS, also as @charlietfl mentioned: if you don't want to mutate objects in arr1
start with empty object ... Object.assign({},arr1[i], arr2[i])
PS,也正如@charlietfl 提到的:如果你不想改变
arr1
对象,从空对象开始...... Object.assign({},arr1[i], arr2[i])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.