在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
中的值存在的元素换句话说,它只会显示蓝色和红色
提前致谢!
最佳答案
给定颜色和汽车阵列,您可以通过以下方式过滤颜色:
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);