Reputation: 161
I have 2 separate array but both of them have same length. How to merge them together into an array object so that it's easy to populate later?
for example
[1,2,3,4,5]
['a','b','c','d','e']
I expect I can have something like
[{'index':1,'value':'a'},{'index':2,'value':'b'}]
I've tried
$.each(a, function(i,x){
$.each(b, function(i,z){
c['index'] = x;
c['value'] = z;
});
});
But I got only [{'index':'1','value':'a'}]
Upvotes: 3
Views: 4586
Reputation: 5937
With ES6 you can do it with arrow function like below:
const arr1 = [1, 2, 3, 4, 5];
const arr2 = ["a", "b", "c", "d", "e"];
const output = arr1.map((el, i) => ({ index: el, value: arr2[i] }));
console.log(output);
Upvotes: 1
Reputation: 115212
You can use map()
for iterate and generate the new array
var arr1 = [1, 2, 3, 4, 5],
arr2 = ['a', 'b', 'c', 'd', 'e'];
var res = arr1.map(function(v, i) {
return {
index: v,
value: arr2[i]
};
})
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
Upvotes: 2