gpt4 book ai didi

javascript - AngularJS - 如何检查特定键在数组中是否具有特定值

转载 作者:行者123 更新时间:2023-11-30 14:50:57 25 4
gpt4 key购买 nike

在 Angular 中,我有一个这样的数组:

$scope.colors =["blue","red","pink","yellow"];

还有一个对象

$scope.cars=[{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];

我想做过滤,这样

<ul>
<li ng-repeat="n in colors | filter:colorFilter">
</li>
</ul>

ng-repeat 只会显示 $scope.colors 中作为值存在于 $scope.cars

中的元素

所以,换句话说,它只会显示蓝色红色

提前致谢!

最佳答案

给定 colorscars 数组,您可以通过以下方式过滤colors:

var colors =["blue","red","pink","yellow"];
var cars=[ {"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];

var filteredColors = colors.filter(color => cars.some(car => car.color === color));

console.log(filteredColors);

如果不能使用ES6,应该是:

var colors =["blue","red","pink","yellow"];
var cars=[ {"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];

var filteredColors = colors.filter(function(color) {
return cars.some(function(car) {
return car.color === color;
});
});

console.log(filteredColors);

关于javascript - AngularJS - 如何检查特定键在数组中是否具有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48113440/

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