Lodash-搜索嵌套数组并返回对象 [英] Lodash - Search Nested Array and Return Object

查看:395
本文介绍了Lodash-搜索嵌套数组并返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Lodash搜索嵌套数组,并希望在找到匹配项时返回该对象.

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

对于每个对象,搜索"Bus 4".如果找到,则返回对象(在这种情况下,学校为"xyz").

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.

推荐答案

首先,我们应该确定要使用的功能.过滤器 https://lodash.com/docs#filter 符合我们的情况,因为我们要返回可以通过的内容我们的评估.

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.

困难的部分是进行评估. lodash确实支持通过嵌套数组进行搜索,一旦学习,语法实际上就非常直观.

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:过滤器将始终返回一个数组,因此,如果仅需要对象,请确保在其后附加[0].

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

这篇关于Lodash-搜索嵌套数组并返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆