当前位置: 首页 > 知识库问答 >
问题:

javascript - 请问大家 两个数组对象的组合方法,谢谢大家?

凌琦
2023-07-12
 let arr1 = [
                  {
                    cart_goods:[{
                      goods_id:1,
                      is_purchase:1,
                      is_checked:false
                    }]
                  },
                  {
                    cart_goods:[{
                      goods_id:2,
                      is_purchase:1,
                      is_checked:false
                    }]
                  }
                ]
let arr2 = [
  {
    cart_goods:[{
      goods_id:1,
      is_purchase:0,
      is_checked:true
    }]
  },
  {
    cart_goods:[{
      goods_id:2,
      is_purchase:0,
      is_checked:true
    }]
  }
]

我想把arr2中的is_checked 属性值 复制给 arr1中的is_checked 想要的结果是:

 let arr1 = [
                  {
                    cart_goods:[{
                      goods_id:1,
                      is_purchase:1,
                      is_checked:true
                    }]
                  },
                  {
                    cart_goods:[{
                      goods_id:2,
                      is_purchase:1,
                      is_checked:true
                    }]
                  }
                ]

以为是个双重循环,有点不知道怎么写

共有3个答案

爱乐邦
2023-07-12

如果你两个索引一致那就双重循环,通过索引去找到对应元素
arr2.forEach((v,i) => v.cart_goods.forEach((e,j) => arr1[i].cart_goods[j].is_checked = e.is_checked))

幸乐湛
2023-07-12

因为是想把arr2is_checked值赋给arr1,所以建议拿arr2来做循环

arr2.forEach((arr2_item, index) => {
    const value = arr2_item.cart_goods[0].is_checked;
    const arr1_item = arr1[index];
    if (arr1_item) {
        arr1_item.cart_goods[0].is_checked = value
    } else {
        return;
    }
});
范麒
2023-07-12
arr1.forEach(({ cart_goods }, i) => {
    cart_goods[0].is_checked = arr2[i].cart_goods[0].is_checked;
});
console.log(arr1);
 类似资料: