given a random datastructure (can be realy anything):
const data = [
{
name: "John",
age: 26,
company: {
name: "Some company",
address: "Some address"
}
},{...}
];
I would like to be able to search in all values of the object and sub objects. For instance if the user types in John, I'd like to return all objects containing "John", and if the User searches for "Some company", I'd like to return the all objects containing theses as well.
I was thinking about flatten the structure ob each object and afterwards filter the original list, but this somehow doesn't feel right. Any suggestions?
You could use a recursive search for objects with Object.values.
var data = [{ name: "John", age: 26, company: { name: "Some company", address: "Some address" } }, { name: "Jane", age: 32, company: { name: "Cameo", address: "2nd Root Dr" } }],
find = 'Cameo',
result = data.filter(o => Object.values(o).some(function search(v) {
return v && typeof v === 'object' ? Object.values(v).some(search) : v === find;
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With