合并两个数组的相同索引对象 [英] Combine same-index objects of two arrays
问题描述
说我有两个对象数组,像这样:
Say I have two arrays of objects, like so:
var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
var arr2 = [{age: 22}, {age: 30}];
我想要一个这样的组合数组:
I want a combined array like so:
var arr3 = [{name: 'jay', age: 22}, {name: 'Bob', age: 30}];
您可以放心地假设两个初始数组的索引将彼此匹配,这意味着arr1的索引0将始终与arr2的索引0匹配.
You can safely assume that the two initial arrays will have indexes matching each other, meaning index 0 of arr1 will always go with index 0 of arr2.
最快的方法是什么?我在想象一个嵌套在另一个forEach
循环内的forEach
循环,并使用arr2
的当前对象扩展arr1
的每个对象,但是我觉得这可能太复杂了.
What would be the fastest way to accomplish this? I was imagining a forEach
loop nested inside another forEach
loop and extending each object from arr1
with the current object from arr2
, but I feel this may be too complex.
推荐答案
您可以迭代一个数组,并使用第一次迭代中的索引创建一个新数组.有很多方法可以做到这一点.这是一个:
You can just iterate one array and create a new array using the index from the first iteration. There are many ways to do this. Here's one:
var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
var arr2 = [{age: 22}, {age: 30}];
var combined = arr1.map(function(item, index) {
return {name: item.name, age: arr2[index].age};
});
document.write(JSON.stringify(combined));
如果您确实想要最大的性能,则必须在许多不同的浏览器中测试多种方案.例如,有时for
循环比某些浏览器中的内置数组方法要快.
If you really want the maximum performance, you'd have to test a number of schemes in a number of different browsers. For example, sometimes a for
loop is faster than the built-in array methods in some browsers.
var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
var arr2 = [{age: 22}, {age: 30}];
var combined = [];
for (var i = 0; i < arr1.length; i++) {
combined[i] = {name: arr1[i].name, age: arr2[i].age};
}
document.write(JSON.stringify(combined));
FYI, the for
loop option (the second option) looks quite a bit faster in all three browsers here in a jsperf.
这篇关于合并两个数组的相同索引对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!