INPUT
let category = [
{
id: 20,
name: "one"
},
{
id: 21,
name: "two"
}
];
let subcategory = [
{
category: 20,
id: 1,
name: "subone"
},
{
category: 21,
id: 2,
name: "subtwos"
},
{
category: 21,
id: 3,
name: "subtwo"
},
{
category: 21,
id: 4,
name: "substwo"
}
];
OUTPUT
let mergedArr = [
{
id: 20,
name: "one",
children: [
{
category: 20,
id: 1,
name: "subone"
}
]
},
{
id: 21,
name: "two",
children: [
{
category: 21,
id: 2,
name: "subtwos"
},
{
category: 21,
id: 3,
name: "subtwo"
},
{
category: 21,
id: 4,
name: "substwo"
}
]
}
];
const result = [...subcategory.reduce(
(acc, n) => (acc.get(n.category)?.children.push(n), acc),
new Map(category.map(n => [ n.id, { ...n, children: [] } ]))
).values()];
const result = category.map(n => ({
...n,
children: subcategory.filter(m => m.category === n.id),
}));
const result = category.map(function(n) {
return {
...n,
children: this[n.id] ?? [],
};
}, subcategory.reduce((acc, n) => ((acc[n.category] ??= []).push(n), acc), {}));