0๐
const list = [
{
"section_title": "title 1",
"section_category": "category1",
"items": [
{
"category": "category1",
"title": "item title 1",
"url": "url 1",
"description": "Etiam turpis ipsum, gravida a odio ac, sollicitudin egestas tortor.",
"footnote": "footnote 1"
},
{
"category": "category1",
"title": "item title 2",
"url": "url 2",
"description": "Suspendisse consectetur lacus sed maximus consectetur. Etiam nunc magna, fringilla.",
"footnote": "footnote 2"
}
]
},
{
"section_title": "title 2",
"section_category": "category2",
"items": [
{
"category": "category2",
"title": "title 3",
"url": "url 3",
"description": "Donec venenatis justo at ligula dictum tempus. In euismod nulla.",
"footnote": "footnote 3"
},
{
"category": "category2",
"title": "title 4",
"url": "url 4",
"description": "Cras dui felis, pulvinar vel elit quis, imperdiet sollicitudin massa.",
"footnote": "footnote 4"
}
]
}
];
const searchString = 'item';
const filteredList = list.filter((section) => {
// `section` here is an arbitrary variable name to represent the individual element in the `listData`
console.log('section', section);
// If section_title contains searchString, add the element to the filtered result
if (section.section_title.indexOf(searchString) > -1) {
return true;
}
// section_title does not contain searchString,
// proceed to check for each section.items if they contain searchString
const hasItemContainsSearchString = section.items.some((item) => {
// `item` here represents the individual element of section.items
console.log('item', item);
// Check if the title contains searchString
return item.title.indexOf(searchString) > -1;
});
return hasItemContainsSearchString;
});
console.log('filteredList', filteredList);
Source:stackexchange.com