Deep searching through a collection with lodash

左心房为你撑大大i 提交于 2019-12-23 05:42:38

问题


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' } ] }, 
]

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

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?


回答1:


Here's a lodash chaining approach:

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

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.




回答2:


You can use javascript reduce function and use where in it :

var elements = array.reduce(function(previous, current) {
    return previous.concat(_.where(current.fields, { type : 'date' }));
}, []);

Lodash version :

var elements = _.reduce(array, function(previous, current) {
    return previous.concat(_.where(current.fields, { type : 'date' }));
}, []);


来源:https://stackoverflow.com/questions/34656120/deep-searching-through-a-collection-with-lodash

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