I have a flat array that i nest together based on childrens parentFolderId. I need to remove items where none of the children, or children’s children below it contains the property in_shop
My example data looks like this:
const menuItems = [
{
id: 1,
displayName: "Equipment",
parentFolderId: null,
// ... rest of object
},
{
id: 2,
displayName: "Equipment",
parentFolderId: 6,
// ... rest of object
},
{
id: 3,
displayName: "Equipment",
parentFolderId: 2,
in_shop: true
// ... rest of object
},
{
id: 4,
displayName: "Equipment",
parentFolderId: 1,
// ... rest of object
},
{
id: 5,
displayName: "Equipment",
parentFolderId: 1,
// ... rest of object
},
{
id: 6,
displayName: "Equipment",
parentFolderId: null,
// ... rest of object
},
{
id: 7,
displayName: "Equipment",
parentFolderId: 5,
in_shop: true,
// ... rest of object
},
{
id: 8,
displayName: "Equipment",
parentFolderId: 3,
// ... rest of object
},
// ... rest of objects
];
I want a result that looks like this, based on the input above:
const menuItems = [
{
id: 1,
displayName: "Equipment",
parentFolderId: null,
// ... rest of object
children: [
{
id: 5,
displayName: "Equipment",
parentFolderId: 1,
children: [
{
id: 7,
displayName: "Equipment",
parentFolderId: 5,
in_shop: true,
// ... rest of object
},
]
// ... rest of object
},
],
},
{
id: 6,
displayName: "Equipment",
parentFolderId: null,
// ... rest of object
children: [
{
id: 2,
displayName: "Equipment",
parentFolderId: 6,
// ... rest of object
children: [
{
id: 3,
displayName: "Equipment",
parentFolderId: 2,
in_shop: true,
// ... rest of object
},
],
},
],
},
// ... rest of objects
]
I cant wrap my head around how to recursively loop from the bottom of the array, then back up.
My code that sorts array under children looks like this:
function addChild(obj) {
// get children and further retrieve its children with map recursively
let children = menuItems.filter(a => a.parentFolderId == obj.id).map(addChild)
// if children are found then add childs in object ALso check if item is in shop
if (children.length > 0 ) {
return { ...obj, children }
}
// if no children found then return object only
return { ...obj }
}
const result = menuItems.filter(a => a.parentFolderId == null).map(addChild)
3
Answers
Updating the return value as follows:
For each an
in_shop
item walk through parents (with caching in an object). Since the order ofin_shop
items seems random – sort the result byid
:You could reduce the tree by looking to children and property
in_shop
.