Quiero fusionar 2 matrices con los mismos campos por gkey pero no quiero anular la primera matriz felids que estoy usando map () y find () pero sobrescribe la primera matriz y la fila indefinida
aquí está mi código
let x = [{id:1 , name: "hi", gkey: 6,np:1000, op:0} ,{id:2 , name: "hello", gkey: 7,np:5000, op:0} ,{id:3 , name: "h", gkey: 8,np:3000, op:0}]; let y = [{id:11,name: "hi" ,gkey:6,np:0,op:100},{id:22,name:"hi",gkey:8,np:0,op:800},]; var marr = x.map(i => y.find(s => s.gkey === i.gkey)) console.log(marr);quiero que mi resultado de combinación de datos sea así:
{id:1 , name: "hi", gkey: 6,np:1000, op:100} {id:2 , name: "hello", gkey: 7,np:5000, op:0} {id:3 , name: "h", gkey: 8,np:3000, op:800}¿alguna solución?
Su código está casi allí, pero debe crear y devolver un objeto combinado:
let x = [{id:1 , name: "hi", gkey: 6,np:1000, op:0} ,{id:2 , name: "hello", gkey: 7,np:5000, op:0} ,{id:3 , name: "h", gkey: 8,np:3000, op:0}]; let y = [{id:11,name: "hi" ,gkey:6,np:0,op:100},{id:22,name:"hi",gkey:8,np:0,op:800},]; var marr = x.map(elX => { const elY = y.find(s => s.gkey === elX.gkey); return { ...elX, np: elX.np + (elY?.np ?? 0), op: elX.op + (elY?.op ?? 0) }; }); console.log(marr);Otras soluciones están bien, pero me preguntaba qué pasa si la operación es realmente una combinación, y la matriz y contiene más elementos que x.
let x = [ { id: 1, name: "hi", gkey: 6, np: 1000, op: 0 }, { id: 2, name: "hello", gkey: 7, np: 5000, op: 0 }, { id: 3, name: "h", gkey: 8, np: 3000, op: 0 }, ]; let y = [ { id: 11, name: "hi", gkey: 6, np: 0, op: 100 }, { id: 22, name: "hi", gkey: 8, np: 0, op: 800 }, { id: 33, name: "new entry in Y arr", gkey: 8, np: 0, op: 5545 }, ]; let result = x.concat(y) .reduce((acc, current) => { let found = acc.find((i) => i["gkey"] === current["gkey"]); if (found) { found.op = current["op"]; return acc; } acc.push(current); return acc; }, []); console.log(result);inserte los elementos de y en x individualmente, como el código a continuación:
let x = [{id:1 , name: "hi", gkey: 6,np:1000, op:0} ,{id:2 , name: "hello", gkey: 7,np:5000, op:0} ,{id:3 , name: "h", gkey: 8,np:3000, op:0}]; let y = [{id:11,name: "hi" ,gkey:6,np:0,op:100},{id:22,name:"hi",gkey:8,np:0,op:800},]; y.forEach(element => { x.push(element) }); console.log(x);