【问题标题】:Filter collection (array of objects) based on other array根据其他数组过滤集合(对象数组)
【发布时间】:2013-10-08 11:57:42
【问题描述】:

我有以下问题。我想根据 fruits 数组过滤这个 fruitsCollection。 我想得到的结果是,例如:

     filteredFruits1 [ all fruits with the 
                       exception of those which are in  
                       fruitsToCut array
                     ]

例子:

var fruitsToCut = [ 'egzotic', 'other'],
    fruitsCollection = [ {name: papaya, type: 'egzotic'}, 
                         {name: orange, type: 'citrus'}, 
                         {name: lemon, type: 'citrus'}
                       ]

也许是一些下划线功能?

【问题讨论】:

    标签: javascript arrays collections underscore.js


    【解决方案1】:

    在现代浏览器上,您可以使用原生的filter

    fruitsCollection.filter(function(fruit) {
      return fruitsToCut.indexOf(fruit.type) === -1;
    } );
    

    否则,您可以以几乎相同的方式使用underscore filter

    _.filter( fruitsCollection, function(fruit) {
      return !_.contains(fruitsToCut, fruit.type);
    } );
    

    另外,您的水果名称需要被引用:

    fruitsCollection = [ {name: 'papaya', type: 'egzotic'}, 
                             {name: 'orange', type: 'citrus'}, 
                             {name: 'lemon', type: 'citrus'}
                           ];
    

    【讨论】:

    • 谢谢 :) - 效果很好,我必须再次阅读所有这些下划线功能。是的,当然我忘记了水果名称的引号;)
    猜你喜欢
    • 2021-03-21
    • 2020-12-14
    • 2019-02-13
    • 2020-10-17
    • 2020-10-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多