简体   繁体   English

将 2 个数组映射到 1 个数组对象

[英]Map 2 array into 1 array object

I have 2 separate array but both of them have same length.我有 2 个单独的数组,但它们的长度相同。 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'}]但我只有[{'index':'1','value':'a'}]

You can use map() for iterate and generate the new array您可以使用map()进行迭代并生成新数组

 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:使用 ES6,您可以使用如下箭头函数来完成:

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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