This is my JSON file:
layers :[
{
key: "1",
title: "Computer Science",
expanded: false,
subLayer: [
{
key: "a",
title: "Programming Language",
expanded: false,
subLayer: [
{
key: "a.1",
title: "HTML",
expanded: false,
subLayer: [],
},
{
key: "a.2",
title: "CSS",
expanded: false,
subLayer: [],
},
],
},
],
},
]
Images:
My question is: When I search Programming Language and Computer Science it appears but if you search for parts in subLayer elements such as HTML and CSS it doesn't appear or can't, why is that? And what needs to be improved from my coding? If I'm writing my code:
const filteredData = data.layers.filter((el) => {
if (props.input === '') {
return el
}
return el.title.toLowerCase().includes(props.input) || el.subLayer.findIndex(x => x.title.toLowerCase().includes(props.input)) >= 0
})
You are only searching the top-most subLayer, which is el.subLayer. You need to search the nested subLayer also. This can be done recursively by looking at whether the current object's title includes your input, and if it doesn't you can check if some object in your subLayer includes the input in the title by recursively calling the search function:
const layers = [{ key: "1", title: "Computer Science", expanded: false, subLayer: [{ key: "a", title: "Programming Language", expanded: false, subLayer: [{ key: "a.1", title: "HTML", expanded: false, subLayer: [], }, { key: "a.2", title: "CSS", expanded: false, subLayer: [], }, ], }, ], }, ];
const hasKeyword = (obj, keyword) => {
return obj.title.toLowerCase().includes(keyword) || obj.subLayer.some(nested => hasKeyword(nested, keyword));
}
const search = (layers, keyword) => {
return layers.filter(obj => hasKeyword(obj, keyword));
}
const res = search(layers, "css");
console.log(res);