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



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

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" ]

您正在使用 Firefox 工作,因此您可能会遇到此类问题,因为问题可能是在 Firefox 的控制台.log如何解释输入对象时引起的。

请看这里

JavaScript 对象中的空插槽?

试试这个

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

尝试以下操作:

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

你的新"数组"不是一个Array,而是一个Object

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

像这样:

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

最新更新