最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash - Search Nested Array and Return Object - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Nov 12, 2015 at 17:14 leejay100 asked Nov 12, 2015 at 16:46 leejay100leejay100 2211 gold badge2 silver badges12 bronze badges 3
  • 1 Your first attempt please. – Ele Commented Nov 12, 2015 at 16:54
  • I actually had the answer written, but I decided to delete it... it's not that hard please try :) – Yichz Commented Nov 12, 2015 at 16:55
  • 1 @Kossel you and me are here to help people and not to do everything. – Ele Commented Nov 12, 2015 at 16:58
Add a comment  | 

1 Answer 1

Reset to default 25

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.

发布评论

评论列表(0)

  1. 暂无评论