To display correctly a Tree view in React, I need to filter a nested tree object.
I find this post : filter nested tree object without losing structure
But actually I would like to do the exactly opposite.
For instance, if in my filterData function name === "a3
" I would like to keep object with name === "a3"
const result = filterData(items, "a3")
const items = [
{
name: "a1",
id: 1,
children: [
{
name: "a2",
id: 2,
children: [
{
name: "a3",
id: 3
},
{
name: "a5",
id: 4
}
]
}
]
},
{
name: "b2",
id: 2,
children: [
{
name: "a2",
id: 2,
children: [
{
name: "a3",
id: 3
}
]
},
{
name: "a4",
id: 8
}
]
}
];
const result = [
{
name: "a1",
id: 1,
children: [
{
name: "a2",
id: 2,
children: [
{
name: "a3",
id: 3
}
]
}
]
},
{
name: "b2",
id: 2,
children: [
{
name: "a2",
id: 2,
children: [
{
name: "a3",
id: 3
}
]
}
]
}
];
You could create new objects without mutating the given data and reduce the arrays.
function filter(array, name) {
return array.reduce((r, { children = [], ...o }) => {
if (o.name === name) {
r.push(o);
return r;
}
children = filter(children, name);
if (children.length) {
r.push(Object.assign(o, { children }));
}
return r;
}, []);
}
var items = [{ name: "a1", id: 1, children: [{ name: "a2", id: 2, children: [{ name: "a3", id: 3 }, { name: "a5", id: 4 }] }] }, { name: "b2", id: 2, children: [{ name: "a2", id: 2, children: [{ name: "a3", id: 3 }] }, { name: "a4", id: 8 }] }];
console.log(filter(items, "a2"));
console.log(filter(items, "a3"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With