Lodash - Search Nested Array and Return Object

11,950

First we should decide what function to use. Filter https://lodash.com/docs#filter fits our case because we want to return something that passes our evaluation.

The difficult part is crafting the evaluation. lodash does support searching through nested arrays, the syntax is actually quite intuitive once you learn it.

_.filter(schools,
  {
    bus: [{id: 4}]
  }
);

As opposed to if bus were not an array in which case it would be

_.filter(schools,
  {
    bus: {id: 4}
  }
);

caveat: filter will always return an array so if you want just the object be sure to append a [0] to it.

Share:
11,950
leejay100
Author by

leejay100

Updated on August 26, 2022

Comments

  • leejay100
    leejay100 over 1 year

    I'm using Lodash to search a nested array and want return the object if it finds a match.

    For each object, search for Bus 4. If found, return the object (in this case, school 'xyz').

    var schools = [  
       {  
          "id":1,
          "school":"abc",
          "bus":[  
             {  
                "id":1,
                "name":"first bus"
             },
             {  
                "id":2,
                "name":"second bus"
             }
          ]
       },
       {  
          "id": 2,
          "school":"xyz",
          "bus":[  
             {  
                "id":3,
                "name":"third bus"
             },
             {  
                "id":4,
                "name":"fourth bus"
             }
          ]
       }
    ]
    

    Here's what I have so far:

    _.forEach(schools, function(school){console.log(_.where(school.bus, {'id':4}))})
    

    Just spitting out the results. Kind of works.

  • leejay100
    leejay100 over 8 years
    Fantastic, thanks Robert. And also thanks for leaving the smug at the door :)
  • Vishu Bhardwaj
    Vishu Bhardwaj about 6 years
    Hi, I used this functionality. It is returning me [ { id: 123, child: [ {id: 34}, {id: 35}, {id: 36} ] } ] when I search for _.filter(insuranceMasterData, { child: { id: 35 } }); But I just what the particular object in child array which has the maching id not the whole array. Any suggestions beside custom loops.
  • shashi verma
    shashi verma over 3 years
    what if we have to search on the basis of name ? Like if I put single char say "a" it should return all the objects which has a in the name. as far as I type it give me the specific result.