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

How to filter objects with another object in Angular?

在字体库上工作,我存储的字体是这样的:

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);
                }
            });
        });
    });
});

在不影响性能的情况下最好的方法是什么,因为将来会有数千个字体对象?

因为你使用下划线,所以使用 filter

来自underscore docs

_.filter(list, predicate, [context]) Alias: select Looks through each value in the list, returning an array of all the values that pass a truth test (predicate).

所以你的过滤器将是(只有当你想为每个对象操作数据时才使用它,否则使用 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) Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.

Underscore 会为您处理性能问题,所以不用担心。

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