SHARKDEV
SHARKDEV

Reputation: 173

Join two objects into one, updating keys

How can I join two arrays, updating the "qty" key without duplicating the "title" key?

Example:

obj1

obj1 = [{
    id: 0,
    qty: 1,
    title: "HEINEKEN0 350ML"
}]

obj2

obj2 = [
    {
        id: 0,
        qty: 5,
        title: "HEINEKEN0 350ML"
    },
    {
        id: 1,
        qty: 1,
        title: "HEINEKEN0 600ML"
    }
];

Output I need:

output = [
    {
        id: 0,
        qty: 6,
        title: "HEINEKEN0 350ML"
    },
    {
        id: 1,
        qty: 1,
        title: "HEINEKEN0 600ML"
    }
 ];

Upvotes: 0

Views: 41

Answers (1)

Unmitigated
Unmitigated

Reputation: 89264

You can concatenate both arrays together and use Array#reduce with an object to store the values for each title.

const obj1 = [{
    id: 0,
    qty: 1,
    title: "HEINEKEN0 350ML"
}],
obj2 = [{
    id: 0,
    qty: 5,
    title: "HEINEKEN0 350ML"
},
{
    id: 1,
    qty: 1,
    title: "HEINEKEN0 600ML"
}];
const res = Object.values([...obj1, ...obj2].reduce((acc,{title,qty,id})=>{
  (acc[title] = acc[title] || {id,qty: 0,title}).qty += qty;
  return acc;
}, {}));
console.log(res);

Upvotes: 1

Related Questions