简体   繁体   中英

How can I merge two object arrays by index in JavaScript?

What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]

Desired output would be:

var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.

I think you are looking for matrix transposition , where the 2d array passed is [array1, array2] .

Edit : It looks like this operation can also be called "zipping" when only two arrays are used. Matrix transposition can support any number of rows, not just two.

 var array1 = [ [1, 2, 3, 4], [4, 5, 6, 7] ] var array2 = [ ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'] ] function transpose(matrix) { return matrix.map(function(_, i) { return matrix.map(function(e) { return e[i] }) }) } var result = transpose([array1, array2]) console.log(result) 
 .as-console-wrapper { min-height: 100%; } 

If you really want to have nested objects with properties array1 and array2 instead of arrays, the following solution should also work (a variation of this answer ):

 var array1 = [ [1, 2, 3, 4], [4, 5, 6, 7] ] var array2 = [ ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'] ] var result = array1.map(function (e1, i) { return { array1: e1, array2: array2[i] } }) console.log(result) 
 .as-console-wrapper { min-height: 100%; } 

This is very similar to How do I zip two arrays in JavaScript? , except you just change the output format from an array to an object:

 var array1 = [[1,2,3,4],[4,5,6,7]]; var array2 = [['a','b','c','d'],['e','f','g','h']]; var array3 = array1.map(function(_, i) { return { array1: array1[i], array2: array2[i] }; }); console.log(array3); 

You can use the array map function:

 var array1 = [[1,2,3,4],[4,5,6,7]]; var array2 = [['a','b','c','d'],['e','f','g','h']]; var array3 = array1.map(function (e, i) { return [e, array2[i]]; }); console.log(array3); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM