I want merge 2 arrays with the same fields by gkey but I don't want to override the first array felids I'm using map() and find() but it overwrites the first array and undefined row
here is my code
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);
i want my merge data result like this:
{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}
any solutions?
CodePudding user response:
Other solutions are just fine, but I was wondering what if the operation is truly a merge one, and the y array contain more items than 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);
CodePudding user response:
Your code is almost there, but have to create and return a merged object:
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);
CodePudding user response:
insert the elements of y into x individually , like code below :
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);