如何在Angular中使用另一个对象过滤对象?

时间:2015-05-07 16:07:42

标签: javascript angularjs performance filter

使用字体库,我存储如下字体:

var fonts = [
    {
        name: "Foo",
        style: "Bar",
        families: [
            { name: "A", parent: "B" },
            { name: "C", parent: "D" }
        ]
    } // and so on...
];

我想过滤掉其家庭列表包含{ name: "A", parent: "B" }的字体。

过滤器看起来像var selection = [{ name: "A", parent: "B" }]

实际上,代码看起来像这样:

// Triggers when a new family is added to the filter
$scope.$on('filter:changed', function(e, selection) {

    _.each($scope.fonts, function(font) {

        _.each(font.families, function(family) {

            _.each(selection, function(item) {

                if(_.isMatch(family, item)) {
                    console.log('font', font);
                    console.log('has a match for family', family);
                } else {
                    console.log('no match for family', family);
                }
            });
        });
    });
});

没有性能影响的最佳方法是什么,因为将来会有数千个字体对象?

2 个答案:

答案 0 :(得分:1)

underscore#where

$scope.$on('filter:changed', function(e, selection) {
    var multiselection,
        singleSelection;
    _.each($scope.fonts, function(font) {
        multiselection = _.where(font.families, { name: "A", parent: "B" }); //all matching objects
        singleSelection = _.findWhere(font.families, { name: "A", parent: "B" }); // single matching object
    });
});

<强> JSFIDDLE

答案 1 :(得分:0)

由于您使用下划线使用filter

来自underscore docs

  

_。filter(list,predicate,[context])别名:选择查看列表中的每个值,返回通过a的所有值的数组   真相测试(谓词)。

所以你的过滤器就是(只有当你想操纵每个对象的数据时才使用它,否则使用where):

var myFamilyMatch = { name: "A", parent: "B" };

var selection = _.filter(fonts, function(font){
  return _find(font.families, function(family){
     return family == myFamilyMatch;
  };
});

或者简单(并且更好)使用where作为@dcodesmith建议:

  

_。where(list,properties)查看列表中的每个值,返回包含所有键值的所有值的数组   在属性中列出的对。

Underscore将为您处理性能,所以不要担心。