I have an array like this
const treeObj = [
{
id: 1,
name: 'Section One',
items: [
{ id: 1, name: 'Section One Item One' },
{ id: 2, name: 'Section One Item Two' },
{ id: 3, name: 'Section One Item Three' },
],
},
{
id: 2,
name: 'Section Two',
items: [
{ id: 1, name: 'Section Two Item One' },
{ id: 2, name: 'Section Two Item Two' },
{ id: 3, name: 'Section Two Item Three' },
],
},
{
id: 3,
name: 'Section Three X',
items: [
{ id: 1, name: 'Section Two Item One' },
{ id: 2, name: 'Section Two Item Two' },
{ id: 3, name: 'Section Two Item Three' },
],
},
{
id: 4,
name: 'Section Four X',
items: [
{ id: 1, name: 'Section Two Item One' },
{ id: 2, name: 'Section Two Item Two' },
{ id: 3, name: 'Section Two Item Three' },
],
},
{
id: 5,
name: 'Section Three X',
items: [
{ id: 1, name: 'Section Two Item One' },
{ id: 2, name: 'Section Two Item Two' },
{ id: 3, name: 'Section Two Item Three' },
],
},
{
id: 6,
name: 'Section Four X',
items: [
{ id: 1, name: 'Section Two Item One' },
{ id: 2, name: 'Section Two Item Two' },
{ id: 3, name: 'Section Two Item Three' },
],
},
];
I need to write a search functionality that searches the array with an input. I need to check whether string typed is matching each the outer name or any of the name inside items in each section.
Like: str === treeObj[0].name or str in any one of treeObj .items[].name
I need the output in same structure. I'm familiar with filter. But i cant find the right way to do this, checking both section name and item names.
Search the array with a string whether it matches eahc section naem or any one of names in items inside
Can someone point me in the right direction?
UPDATE
I tried this
const searchStr = searchText.toLowerCase();
filteredData = data.filter(obj => {
if (obj.name.toLowerCase().includes(searchStr)) {
return true;
}
if (obj.items.find(item => item.name.toLowerCase().includes(searchStr))) {
return true;
}
return false;
});
But it returns all items in a section. doesn't filter each section. I need to search to work for both section and items (Try searching an item like: Section One Item One)