在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
因此,换句话说,它只会显示蓝色和红色
提前致谢!
答案 0 :(得分:1)
您可以使用map
方法作为参数接受回调函数,以便从$scope.cars
获取每个汽车项目的所有颜色,然后使用Set
构造函数进行查找出unique
种颜色。然后你必须使用filter
函数。
然后你必须使用filter
函数。
let colors =["blue","red","pink","yellow"];
let cars = [{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];
let uniqueColours= [...new Set(cars.map(c => c.color))];
const filteredColors = colors.filter(a=>uniqueColours.includes(a));
console.log(filteredColors);
&#13;
您可以在一行中执行此操作:
const colors =["blue","red","pink","yellow"],cars = [{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}],
filteredColors = colors.filter(a => cars.map(a => a.color).includes(a));
console.log(filteredColors);
&#13;
没有箭头功能。
const colors =["blue","red","pink","yellow"],cars = [{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}],
filteredColors = colors.filter(function(a){
return cars.map(function(c){
return c.color;
}).includes(a)});
console.log(filteredColors);
&#13;
答案 1 :(得分:1)
鉴于 colors 和 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);
&#13;
如果你不能使用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);
&#13;