Search code examples
javascriptjsonlodash

lodash filter by name


I'm trying to figure out how to use lodash to filter the following object:

contacts = {
  A: [
  { name: "Albert", age: 16 },
  { name: "Arthur", age: 24}
  ],
  B: [
  { name: "Bob", age: 33 }
  ],
  C: [],
  D: [],
...
};

I'd like to be able to filter contacts by name (contains) while keeping the same structure, I don't know to tell lodash to look for any objects on the 2nd level.

Any idea how to go about this?


Solution

  • Try this one

    const contacts = {
      A: [
      { name: "Albert", age: 16 },
      { name: "Arthur", age: 24}
      ],
      B: [
      { name: "Bob", age: 33 },
      { name: "Ahn", age: 20 },
      ],
      C: [],
      D: []
    };
    
    const obj = {};
    Object.keys(contacts).forEach(index => {
      obj[index] = contacts[index].filter(person =>
        person.name.includes("th"));
    });
    console.log(obj);