【问题标题】:How to replace specific key elements in array with elements of another array如何用另一个数组的元素替换数组中的特定关键元素
【发布时间】:2020-06-10 15:47:46
【问题描述】:

我有一个可变长度的数组对象,我想用另一个长度可变的数组对象替换整个数组的特定关键元素。我尝试了不同的数组方法,但我被困在这个方法上。我有 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.length === b.length吗?
  • 是 a.length===b.length

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

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

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

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    为简单起见,这是需要做的事情

    for( let index = 0; index < objectArray.length; index++ ){
    
       objectArray[index].qty = qtys[index].qty;
    
    }
    

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

    比如初始化objectArray后在控制台运行这个

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

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

    【讨论】:

      猜你喜欢
      • 2013-07-04
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2012-11-13
      • 2020-03-19
      • 2016-11-11
      相关资源
      最近更新 更多