Tengo dos conjuntos de objetos y quiero obtener uno nuevo que sea una combinación de esos dos.
const all_products = [ { id : 1, name : "Coca Cola", price : 12.34 }, { id : 2, name : "Marbo Chips", price : 8.34 }, { id : 3, name : "Seven Days", price : 4.34 }, { id : 4, name : "Lays", price : 32.34 }, { id : 5, name : "Pringles", price : 2.34 } ];Y éste:
const shopping_cart = [ { id : 1, qty : 4 }, { id : 5, qty : 2 } ];Quiero filtrar a través de la matriz all_products comparando si las identificaciones son las mismas y quiero agregar una cantidad a ese objeto y obtener esto
new_arr = [ { id: 1, name: "Coca Cola", price: 12.34, qty: 4 }, { id: 5, name: "Pringles", price: 2.34, qty: 2 }]He tenido éxito al usar esto
const test = []; for( let one_product of all_products ) { for( let sc_item of shopping_cart ){ if(one_product.id === sc_item.id){ let it = { ...one_product, qty : sc_item.qty } test.push(it); } } }Pero quiero hacer esto usando funciones de matriz js como filtrar, algunas, reducir, etc.
hola ,
este es tu codigo
const all_products = [ { id : 1, name : "Coca Cola", price : 12.34 }, { id : 2, name : "Marbo Chips", price : 8.34 }, { id : 3, name : "Seven Days", price : 4.34 }, { id : 4, name : "Lays", price : 32.34 }, { id : 5, name : "Pringles", price : 2.34 } ]; const shopping_cart = [ { id : 1, qty : 4 }, { id : 5, qty : 2 } ]; const test = []; all_products.forEach(one_product => { shopping_cart.forEach(sc_item => { if(one_product.id === sc_item.id){ let it = { ...one_product, qty : sc_item.qty } test.push(it); } }) }) console.log(test)Ahí tienes
const all_products = [{ id: 1, name: "Coca Cola", price: 12.34 }, { id: 2, name: "Marbo Chips", price: 8.34 }, { id: 3, name: "Seven Days", price: 4.34 }, { id: 4, name: "Lays", price: 32.34 }, { id: 5, name: "Pringles", price: 2.34 } ]; const shopping_cart = [{ id: 1, qty: 4 }, { id: 5, qty: 2 } ]; const updatedCart = shopping_cart.map((item) => { const moreProductInfo = all_products.filter((product) => product.id === item.id)[0]; return { ...item, ...moreProductInfo } }) console.log(updatedCart)Si desea mantener las entradas no coincidentes:
var merged = all_products.filter(function(a) { return shopping_cart.filter(function(b){ if (a.id == b.id) { return Object.assign(a, b) } }) });