I came across an issue I don't manage to fix currently. It's about grouping values in an Array together, that will be used later for displaying product filters in React.
Let's consider the following as an input example:
const input = [
{ id: '11111_11111', title: 'Parent 1' },
{ id: '22222_22222', title: 'Parent 2' },
{ id: '33333_33333', title: 'Parent 3' },
{ id: '44444_44444', title: 'Parent 4', key: "root_parent" },
{ id: '11111_11111_11111', parentId: '11111_11111', title: 'Child 1' },
{ id: '11111_11111_22222', parentId: '11111_11111', title: 'Child 2' },
{ id: '22222_22222_11111', parentId: '22222_22222', title: 'Child 3' },
{ id: '22222_22222_22222', parentId: '22222_22222', title: 'Child 4' },
{ id: '22222_22222_33333', parentId: '22222_22222', title: 'Child 5' },
{ id: '33333_33333_11111', parentId: '33333_33333', title: 'Child 6' },
{ id: '44444_44444_11111', parentId: '44444_44444', title: 'Child 7' },
{ id: '44444_44444_44444_11111', parentId: '44444_44444_11111', title: 'Child 8' },
];
The output should look like the following:
[
{
rootParent: {},
filter: { id: "11111_11111", title: "Parent 1" },
options: [
{ id: "11111_11111_11111", parentId: "11111_11111", title: "Child 1" },
{ id: "11111_11111_22222", parentId: "11111_11111", title: "Child 2" },
]
},
{
rootParent: {},
filter: { id: "22222_22222", title: "Parent 2" },
options: [
{ id: "22222_22222_11111", parentId: "22222_22222", title: "Child 3" },
{ id: "22222_22222_22222", parentId: "22222_22222", title: "Child 4" },
{ id: "22222_22222_33333", parentId: "22222_22222", title: "Child 5" },
]
},
{
rootParent: {},
filter: { id: "33333", title: "Parent 3" },
options: [
{ id: "33333_33333_11111", parentId: "33333_33333", title: "Child 6" },
]
},
{
rootParent: { id: '44444_44444', title: 'Parent 4', key: "root_parent" },
filter: { id: '44444_44444_11111', parentId: '44444_44444', title: 'Child 7' },
options: [
{ id: '44444_44444_44444_11111', parentId: '44444_44444_11111', title: 'Child 8' },
]
}
]
I could manage to group the filter and options values together properly, but I'm really struggling at the moment with that rootParent level.
Here`s what I got so far:
const groupFilters = (arr) => {
let result = [];
const parents = arr?.filter((item) => !('parentId' in item));
result = parents?.map((parent) => ({ filter: parent, options: [] }));
const options = arr?.filter((item) => 'parentId' in item);
options?.forEach((option) => {
result?.forEach((parent) => {
if (option.parentId === parent?.filter?.id) {
parent.options.push(option);
}
});
});
return result;
};
It would be amazing if some of you could help me fixing this issue. Maybe there's also a "cleaner" way to accomplish it. To be honest, nested forEach() loops don't feel good.
Thanks a lot in advance!