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

时间:2015-11-27 11:40:48

标签: javascript jquery arrays

我有2个单独的数组,但它们都有相同的长度。如何将它们合并到一个数组对象中,以便以后容易填充?

例如

[1,2,3,4,5]
['a','b','c','d','e']

我希望我能有像

这样的东西
[{'index':1,'value':'a'},{'index':2,'value':'b'}]

我试过

    $.each(a, function(i,x){

      $.each(b, function(i,z){
        c['index'] = x;
        c['value'] = z;
      });

    });

但我只得到[{'index':'1','value':'a'}]

1 个答案:

答案 0 :(得分:1)

您可以使用 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>');

相关问题