how to find all matching values based on search input of objects for the nested array of objects
const data = [ { name: "testmapping", items: [ { name: "lv2test1mapping", items: [ { name: "lv3test1mapping" }, { name: "lv3test2mapping" }, { name: "lv3test3mapping" } ] }, { name: "lv2test2mapping" }, { name: "lv2test3mapping" } ] }, { name: "test2mapping", items: [ { name: "lv2test21mapping", items: [ { name: "lv3test21mapping" }, { name: "lv3test22mapping" }, { name: "lv3test23mapping" } ] }, { name: "lv2test22mapping" }, { name: "lv2test23mapping" } ] }];function getValue(searchText) { const localData = [...data]; function getValueLogic(data, searchText) { const arr = []; if (data && Array.isArray(data)) { for (let i = 0; i < data.length; i++) { const ele = data[i]; ele && ele.name.includes(searchText) ? arr.push(ele) : arr.push(...getValueLogic(ele.items, searchText)); } } return arr; } return getValueLogic(localData, searchText);}console.log("one level", getValue("test"));console.log("second level", getValue("lv2"));console.log("third level", getValue("lv3"));console.log("Actual Data", data);
Recursion
is the key! The below function should meet your requirement.
const data = [...] //your datafunction getValue(searchText) { const localData = [...data]; function getValueLogic(data, searchText) { const arr = []; if (data && Array.isArray(data)) { for (let i = 0; i < data.length; i++) { const ele = data[i]; ele && ele.name.includes(searchText) ? arr.push(ele) : arr.push(...getValueLogic(ele.items, searchText)); } } return arr; } return getValueLogic(localData, searchText);}console.log("one level", getValue("test"));console.log("second level", getValue("lv2"));console.log("third level", getValue("lv3"));console.log("Actual Data", data);