[英]Lodash - Search Nested Array and Return Object
I'm using Lodash to search a nested array and want return the object if it finds a match. 我正在使用Lodash搜索嵌套数组,并希望在找到匹配项时返回该对象。
For each object, search for Bus 4. If found, return the object (in this case, school 'xyz'). 对于每个对象,搜索总线4.如果找到,则返回对象(在本例中为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.
有点作品。
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.
过滤https://lodash.com/docs#filter符合我们的要求,因为我们想要返回通过评估的内容。
The difficult part is crafting the evaluation. 困难的部分是制定评估。 lodash does support searching through nested arrays, the syntax is actually quite intuitive once you learn it.
lodash确实支持通过嵌套数组进行搜索,一旦你学会了它,语法实际上非常直观。
_.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]附加到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.