Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a complicated data structure

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?

like image 267
Christian Avatar asked Aug 03 '26 22:08

Christian


1 Answers

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; }
like image 149
Nina Scholz Avatar answered Aug 06 '26 10:08

Nina Scholz