Lodash: how do I use filter when I have nested Object?

前端 未结 5 519
滥情空心
滥情空心 2020-12-07 16:40

Consider this example. I am using Lodash

 \'data\': [
        {
            \'category\': {
                \'uri\': \'/categories/0b092e7c-4d2c-4eba-8c4e-80         


        
相关标签:
5条回答
  • 2020-12-07 16:44

    beginning from v3.7.0 you can do it in this way:

    _.filter(summary.data, 'category.parent', 'Food')
    
    0 讨论(0)
  • 2020-12-07 16:47
    _.where(summary.data, {category: {parent: 'Food'}});
    

    Should do the trick too

    0 讨论(0)
  • 2020-12-07 16:50
    _.filter(summary.data, function(item){
      return item.category.parent === 'Food';
    });
    
    0 讨论(0)
  • 2020-12-07 16:52

    lodash allows nested object definitions:

    _.filter(summary.data, {category: {parent: 'Food'}});
    

    As of v3.7.0, lodash also allows specifying object keys in strings:

    _.filter(summary.data, ['category.parent', 'Food']);
    

    Example code in JSFiddle: https://jsfiddle.net/6qLze9ub/

    lodash also supports nesting with arrays; if you want to filter on one of the array items (for example, if category is an array):

    _.filter(summary.data, {category: [{parent: 'Food'}] }); 
    

    If you really need some custom comparison, that's when to pass a function:

    _.filter(summary.data, function(item) {
      return _.includes(otherArray, item.category.parent);
    });
    
    0 讨论(0)
  • 2020-12-07 17:00

    In lodash 4.x, you need to do:

    _.filter(summary.data, ['category.parent', 'Food'])
    

    (note the array wrapping around the second argument).

    This is equivalent to calling:

    _.filter(summary.data, _.matchesProperty('category.parent', 'Food'))
    

    Here are the docs for _.matchesProperty:

    // The `_.matchesProperty` iteratee shorthand.
    _.filter(users, ['active', false]);
    // => objects for ['fred']
    
    0 讨论(0)
提交回复
热议问题