Quiero que el resultado sea sumar todas las cantidades del mismo gato.
var data = [ { cat: 'EK-1',name:"test",info:"mat", quantity: 3}, { cat: 'EK-2', name:"test2",info:"nat"quantity: 1} ];Intenté así a continuación. Tengo una matriz de objetos que tienen algunos objetos similares. cómo agregar cantidad y crear objetos únicos. A continuación he dado lo que probé.
var data = [{ cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-2', name: "test2", info: "nat", quantity: 1 } ]; const products = Array.from(data.reduce((acc, { cat, quantity }) => acc.set(cat, (acc.get(cat) || 0) + quantity), new Map() ), ([cat, quantity]) => ({ cat, quantity })); console.log(products);Puedes hacer esto usando Array#reduce , usando el acumulador para pasar el nuevo objeto:
var data = [ { cat: "EK-1", name: "test", info: "mat", quantity: 1, }, { cat: "EK-1", name: "test", info: "mat", quantity: 1, }, { cat: "EK-1", name: "test", info: "mat", quantity: 1, }, { cat: "EK-2", name: "test2", info: "nat", quantity: 1, }, ]; let seen = []; const res = data.reduce((acc, { cat, ...rest }) => { const idx = seen.indexOf(cat); if (idx == -1) (acc.push({cat, ...rest}), seen.push(cat)); else acc[idx].quantity++; return acc; }, []); console.log(res);