gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:20:05 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于javascript - 如何在 Angular 中用另一个对象过滤对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30106372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com