2017-10-06 141 views
-2

这可能是有点复杂的问题,创建动态对象/从多个阵列阵列 - 的Javascript

我有2个阵列中的javascript

  1. 组合
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

+1

无论您尝试过什么都应该发布为[mcve] – zer00ne

+0

为什么'500'和'350'被列为结果数组的预期值? – guest271314

+0

提供的缺陷代码中的第一个数组阵列与图像不匹配。有没有一个过程中的代码成为无用图像中描绘的内容? – zer00ne

回答

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)

+0

先生,令人惊叹。我只需要改变'newitem [rowItem [0]] = item [rowItem [1]];''newitem [rowItem [1]] = item [rowItem [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));