从多个数组创建动态对象/数组 - Javascript

时间:2017-10-06 05:58:59

标签: javascript jquery arrays

这可能是一个小问题,

我在 javascript

中有2个数组
  1. 结合
  2.  rows = [
               ["0324444444", "3510254373", "35000", "5000"],
               ["0323434444", "3510466773", "32000", "5300"],
               ["0324444564", "3310254373", "32300", "5450"]
        ]
    
         

    combined = [['mobile', 0], ['cnic', 1], ['salary', 2], ['tax', 3]]

    现在我想合并(或者可以说"用它们制作第三个数组")就像这样。

    enter image description here

2 个答案:

答案 0 :(得分:2)

只需尝试

var rows = [
  ["0324444444", "3510254373", "35000", "5000"],
  ["0323434444", "3510466773", "32000", "5300"],
  ["0324444564", "3310254373", "32300", "5450"]
];
var combined = [
  ['mobile', 0],
  ['cnic', 1],
  ['salary', 2],
  ['tax', 3]
];
var output = rows.map(function(item) {
  var obj = {};
  combined.forEach(function(key) {
    obj[key[0]] = Number(item[key[1]])
  });
  return obj;
});

console.log(JSON.stringify(output, 0, 4));

答案 1 :(得分:2)

可以这样做



var rows = [
           ["0324444444", "3510254373", "35000", "5000"],
           ["0323434444", "3510466773", "32000", "5300"],
           ["0324444564", "3310254373", "32300", "5450"]
    ]
var combined  = [['mobile', 0], ['cnic', 1], ['salary', 2], ['tax', 3]]

var final = [];
rows.forEach(function(item){
     var newitem = {};
     combined.forEach(function(rowItem, index){
          newitem[rowItem[0]] = item[rowItem[1]];
     })
     final.push(newitem);
});

console.log(final)




相关问题