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 };
});
});
2 Answers 2
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
lissettdm
13.2k1 gold badge25 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Siva Kondapi Venkata
11.1k2 gold badges20 silver badges32 bronze badges
Comments
lang-js