Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

javascript - 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}];

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...