1

I have the following arrays:

 [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Medium'}]
 [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Light'}]

I need to merge them in something like:

[{id:0,name:'Weight',options:['250']},{id:0,name:'Roast',options:['Medium','Light']}]

I tried to nest some loops also tried with merge, push and spread operators but I can't solve it

result.forEach((att) => {
 let newoptions = [];
 console.log('att', att.attributes);
 att.attributes.forEach((id, idx) => {
 console.log('id', id);
 newoptions = [...newoptions, { option: id.option }];
 newAttr[idx] = { name: id.name, options: newoptions };
 });
});
lissettdm
13.2k1 gold badge25 silver badges43 bronze badges
asked Dec 8, 2020 at 14:14

2 Answers 2

1

I recommend you to concat both arrays and then iterate over it. Then reduce the items with Array.prototype.reduce():

const data1 = [{ id: 0, name: "Weight", option: "250" },{ id: 0, name: "Roast", option: "Medium" }];
const data2 = [{ id: 0, name: "Weight", option: "250" },{ id: 0, name: "Roast", option: "Light" }];
const array = [...data1, ...data2]; // concat
const result = array.reduce((o, c) => {
 const exist = o.find(item => item.id === c.id && item.name === c.name);
 if (!exist) {
 const options = array
 .filter(item => item.id === c.id && item.name === c.name)
 .map(item => item.option);
 o.push({ id: c.id, name: c.name, options: Array.from(new Set(options)) });
 }
 return o;
}, []);
console.log(result);

answered Dec 8, 2020 at 14:49
Sign up to request clarification or add additional context in comments.

Comments

1

Use flat and forEach. Build an object with keys as name and aggregate the values.

const process = (...data) => {
 const res = {};
 data.flat().forEach(({ name, option, id }) => {
 res[name] ??= { name, id, options: [] };
 !res[name].options.includes(option) && res[name].options.push(option);
 });
 return Object.values(res);
};
const arr1 = [
 { id: 0, name: "Weight", option: "250" },
 { id: 0, name: "Roast", option: "Medium" },
];
const arr2 = [
 { id: 0, name: "Weight", option: "250" },
 { id: 0, name: "Roast", option: "Light" },
];
console.log(process(arr1, arr2));

answered Dec 8, 2020 at 16:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.