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'}]
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>');
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);
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.