您需要找到所有重复项products.id
并合并quantity
。结果应该是这样的:
products = [{id: 5, quantity: 25}, {id: 3, quantity: 15}, {id: 4, quantity: 164}]
const arr = [{
id: 1,
products: [{
id: 5,
quantity: 5
}, {
id: 3,
quantity: 2
}]
},
{
id: 2,
products: [{
id: 4,
quantity: 75
}, {
id: 5,
quantity: 20
}]
},
{
id: 3,
products: [{
id: 3,
quantity: 13
}, {
id: 4,
quantity: 89
}]
},
]
let allProducts = [];
let products = [];
function getAllProducts() {
arr.forEach(value => {
value.products.forEach(product => allProducts.push(product))
})
concatProducts(allProducts)
}
function concatProducts(arr) {
arr.reduce(function(a, b) {
return a.id === b.id ? products.push({
id: a.id,
quantity: a.quantity + b.quantity
}) : products.push(b);
});
console.log(products)
}
getAllProducts()
2 个回答