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
Solution 1:
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] }
Post a Comment for "How To Combine Two Arrays Into An Array Of Objects In Javascript?"