I have 2 arrays of objects:
array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
I want to merge them so it looks like this:
[{"id":1,"cost":200,"qty":56,"desc":"a good one"},{"id":2,"cost":100,"qty":16,"desc":"a bad one"}];
Please notice the new array has properties from both arrays but it left out the object that was not present in the first one.
I tried this:
var mergethem = function() {
var array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
var array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
var newarray= array2.filter(i => array1.map(a=> { if(a.id == i.id) i.qty = a.qty; return i; }));
return newarray.filter(i=> { if(i.qty) return i; });
}
console.log(mergethem());
this seems to work sometimes and some times it doesn’t depending on the environment. I can’t pinpoint what the problem is so I would like to ask for alternatives to try out.
2
Answers
You could get references of the objects of the second array and map the first while adding properties of the second array, if exist.