Here's the array that I got, and my purpose is to filter this whole array of objects and to return an array of object with founded name ( even if it's located in the nested deepest level of children's). For example, If I am filtering by "Model8", the return value of my function has to be = [{ name: "Model8", type: "file", path: "/path/to/file" }]
const arr = [
{
name: "Model",
type: "directory",
path: "/path/to/folder",
children: [
{
name: "Model1",
type: "file",
path: "/path/to/file",
children: [
{
name: "Model2",
type: "file",
path: "/path/to/file",
children: [
{
name: "Model3",
type: "file",
path: "/path/to/file",
children: [
{ name: "Model4", type: "file", path: "/path/to/file" },
],
},
],
},
],
},
],
},
{
name: "Inventory",
type: "directory",
path: "/path/to/folder",
children: [{ name: "inventory.yaml", type: "file", path: "/path/to/file" }],
},
{
name: "UI",
type: "directory",
path: "/path/to/folder",
children: [
{ name: "elements", type: "directory", path: "/path/to/file" },
{ name: "viewmodel", type: "directory", path: "/path/to/file" },
{ name: "i18n", type: "directory", path: "/path/to/file" },
{
name: "index.template.html",
type: "file",
path: "/path/to/file",
children: [
{
name: "Model5",
type: "file",
path: "/path/to/file",
children: [
{
name: "Model6",
type: "file",
path: "/path/to/file",
children: [
{
name: "Model7",
type: "file",
path: "/path/to/file",
children: [
{ name: "Model8", type: "file", path: "/path/to/file" },
],
},
],
},
],
},
],
},
],
},
{ name: "DeviceConnector", type: "directory", children: [] },
];
I've come up with 2 options :
1)
function searchFilter(searchVal,arr) {
const res = arr.filter(function filteredList(el) {
if (el.children) {
el.children = el.children.filter(filteredList);
}
if (el.name.toLowerCase().includes(searchVal.toLowerCase())) return true;
return res;
});
}
searchFilter("Model8",arr)
But the main problem right here is that for some reason I can't "access 'res' before initialization"
2)
function searchFilter(arr, name) {
const searchItem = arr.find((i) => i.name === name);
if (!searchItem) {
return arr.filter((i) => searchFilter(i.children, name));
}
return searchitem;
}
And here, I can't get lower than first iterated object of an array. The max depth is the object with "Model3" name property.