如何用另一个数组的元素替换数组中的特定关键元素

How to replace specific key elements in array with elements of another array

我有一个可变长度的数组对象,我想用另一个同样可变长度的数组对象替换整个数组的特定关键元素。我尝试了不同的数组方法,但我被困在了这个方法上。我有 6 个月的编程经验。

我的代码是:

a = [
 { id: 1, name: "Alex", qty: 6, prodCode: 1321 }, 
 { id: 2, name: "carry", qty: 2, prodCode: 1641 }, 
 { id: 1, name: "manuel", qty: 7, prodCode: 1754 },
.....]

b= [{qty:5},{qty:9},{qty:2},...]
a.length===b.length

结果应该是这样的:

[
  { id: 1, name: "Alex", qty: 5, prodCode: 1321 }, 
  { id: 2, name: "carry", qty: 9, prodCode: 1641 }, 
  { id: 1, name: "manuel", qty: 2, prodCode: 1754 },
.....]

如果我理解的很好,你可以试试这个:

a.forEach((itemA, index) => {
    itemA.qty = b[index].qty
});

希望对你有帮助。

为简单起见,这就是需要完成的工作

for( let index = 0; index < objectArray.length; index++ ){

   objectArray[index].qty = qtys[index].qty;

}

您可以使用浏览器的 js 控制台了解每个值在 JSON 对象中的位置以及如何从中获取值。

例如运行初始化objectArray后控制台中的this

objectArray[0].qty // This will give qty of the first object in the array

您可以使用它在复杂对象中导航