简体   繁体   中英

How to combine two arrays into an array of objects in javascript?

I have two arrays and I want to form an array of objects such that the new array of obj has two keys with first key being filled with elements of first array and second key having arrays elements of second array. Can this be done using the map function. I found the closest answer as this:- Merge two arrays into an array of objects with property values

eg.:-

ar1=[];
ar2=[];
armixed=[{ar1element,ar2element},{}......]

But it uses angular JS I just want to use pure JS.

I'm not sure what your output should be but the one you provided seems invalid. I have modified the output format to be valid.

For the task you have the solution is to zip the arrays, however, JS has no inbuilt zip function, so we can emulate it via map function:

var ar1 = ['a1', 'a2', 'a3', 'a4', 'a5'];
var ar2 = ['b1', 'b2', 'b3', 'b4', 'b5'];
var armixed = ar1.map(function (x, i) { 
                          return [x, ar2[i]] 
                      });

Output will be:

armixed = [
    ["a1", "b1"]
    ["a2", "b2"]
    ["a3", "b3"]
    ["a4", "b4"]
    ["a5", "b5"]
]

If you want objects in your output (rather than arrays), you can just edit the return statement above to something like:

return { categories: x, catid: ar2[i] }

Just to clarify, do you want an object for each unique possible combination of the arrays? If so, nesting two map functions should do the trick:

 let newArray = [{}] arr1.map(i => { arr2.map (j => { newArray.push({prop1: i, prop2: j}) }) })

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