使用lodash深度搜索集合 [英] Deep searching through a collection with lodash

查看:504
本文介绍了使用lodash深度搜索集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象类似的数组:

I have an array with objects like so:

[ 
    { phase: 1, fields: [ { id: 1, type: 'string' }, { id: 2, type: 'date' } ] }, 
    { phase: 2, fields: [ { id: 3, type: 'date' }, { id: 4, type: 'date' } ] }, 
    { phase: 3, fields: [ { id: 5, type: 'string' }, { id: 6, type: 'date' } ] }, 
    { phase: 4, fields: [ { id: 7, type: 'date' }, { id: 8, type: 'string' } ] }, 
]

我想搜索此数组并返回一个仅包含类型为date的字段的数组.

I want to search through this array and return an array with only the fields that have type date.

我一直在研究lodash函数filterwhere,但是看来过滤器只能浏览一级深度的项目,而我的数组具有多个级别,而搜索条件位于数组的第二级.解决这个问题的最佳策略是什么?

I have been looking at the lodash functions filter and where but it seems filter can only look through items one level deep, whereas my array has multiple levels and my search criterium is in the second level of the array. What would be the best strategy to approach this problem?

推荐答案

以下是lodash链接方法:

Here's a lodash chaining approach:

_(coll)
  .pluck('fields')
  .flatten()
  .filter({ type: 'date' })
  .value();

pluck()调用将构建一个包含所有field值的数组,这些值也都是数组.这就是为什么我们接下来调用 flatten()的原因-创建一个大数组.然后,很容易使用 filter()来获得所需的东西.

The pluck() call builds an array of all the field values, which are also arrays. This is why we call flatten() next - to make one big array. Then it's easy to use filter() to get what you need.

这篇关于使用lodash深度搜索集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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