Javascript两个数组合并(键和值)

时间:2018-01-08 06:00:16

标签: javascript arrays merge key

我有两个阵列。我想将这两个数组合并为一个数组。一个数组包含键和另一个值。我的数组看起来像

productId = [8,7,9];//Key Element
quantity = ["5","1","3"];//Value Element
//expected new array
newarray = {
    "8": 5,
    "7": 1,
    "9": 3
}

我已经尝试以这种方式合并这些数组

var newArray = {};
for(var i=0; i< productId.length; i++){
  newArray[productId[i]] = quantity [i];
}
console.log(newArray);

返回

Object [ <7 empty slots>, "5", "1", "3" ]

3 个答案:

答案 0 :(得分:0)

尝试以下方法:

var productId = [8,7,9];//Key Element
var quantity = ["5","1","3"];//Value Element

var obj = {};
var i = 0;
for(var k of productId) {
    obj[k] = parseInt(quantity[i]);
    i++;
}
console.log(obj);

答案 1 :(得分:0)

您正在使用Firefox,因此您可能会遇到此类问题,因为问题可能是由于Firefox&#39; console.log已解释输入对象。

请看这里

Empty slots in JavaScript objects?

试试这个

&#13;
&#13;
var productId = [8,7,9];
var quantity = ["5","1","3"];
var newarray = {};
productId.forEach((key, i) => newarray[key] = quantity[i]);
console.log(newarray);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你的新&#34;阵列&#34;不是Array,而是Object

您可以使用Array.reduce迭代其中一个数组来构造对象。

类似的东西:

&#13;
&#13;
const arr1 = ['8', '2', '4'];
const arr2 = ['28', '12', '45'];

const result = arr1.reduce((obj, currentItem, index) => {
  obj[currentItem] = arr2[index];
  return obj;
}, {});

console.log(result);
&#13;
&#13;
&#13;

相关问题