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

 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

}]

}

]

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


回答:

arr1.forEach(({ cart_goods }, i) => {

cart_goods[0].is_checked = arr2[i].cart_goods[0].is_checked;

});

console.log(arr1);


回答:

因为是想把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;

}

});


回答:

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


回答:

let newArr = arr1.map((item, index) => {

let newItem = Object.assign({}, item);

newItem.cart_goods = item.cart_goods.map((cartItem, cartIndex) => {

return {

...cartItem,

is_checked: arr2[index].cart_goods[cartIndex].is_checked

};

});

return newItem;

});

console.log(newArr);


回答:

let result = arr1.reduce((acc, item, index) => {

let newItem = {...item};

newItem.cart_goods = newItem.cart_goods.map((cartItem, cartIndex) => {

return {

...cartItem,

is_checked: arr2[index].cart_goods[cartIndex].is_checked

};

});

acc.push(newItem);

return acc;

}, []);

console.log(result);

以上是 请问大家 两个数组对象的组合方法,谢谢大家? 的全部内容, 来源链接: utcz.com/p/934589.html

回到顶部