So i have an array with many objects, all those objects have maybe arrays and objects, so this similar tree continuese, and I want to do a search that searches all values on all those arrays and objects and returns back.
Here is the function I have but doesn't work And I think it works only with the first object but this still is not working.
Here is the function I do have (its broken):
const findIn = (arr, query) => {
let queryFormatted = query.toLowerCase().replace(/\s/g, ' ');
return arr.filter((obj) =>
Object.keys(obj).some((key) => {
if (typeof obj[key] === 'string') {
return obj[key]
.toLowerCase()
.replace(/\s/g, ' ')
.includes(queryFormatted);
}
return false;
})
);
};
Sample of Data (that needs to be searched):
If I understand your question correctly, and you want to check whether any nested string is a substring of your query, returning true or false, here is a solution:
const findIn = (elem, query) => {
query = query.toLowerCase().replace(/\s/g,'');
if (!(elem instanceof Object)){
if (typeof elem == "string"){
return elem.toLowerCase().replace(/\s/g,'').includes(query);
}
return false
}
if (Array.isArray(elem)){
for (const nested of elem){
if (findIn(nested,query)){
return true;
}
}
return false;
}
for (const nested of Object.values(elem)){
if (findIn(nested,query)){
return true;
}
}
return false;
}
Note that this might not work in some specific cases but should be enough if you are parsing json into a js object and then calling the function.