Lodash - Search Nested Array and Return Object

梦想与她 提交于 2019-12-12 14:30:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33676823/lodash-search-nested-array-and-return-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!