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

时间:2018-01-05 12:14:18

标签: javascript html arrays angularjs

在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

中的值存在的元素

因此,换句话说,它只会显示蓝色红色

提前致谢!

2 个答案:

答案 0 :(得分:1)

您可以使用map方法作为参数接受回调函数,以便从$scope.cars获取每个汽车项目的所有颜色,然后使用Set构造函数进行查找出unique种颜色。然后你必须使用filter函数。

然后你必须使用filter函数。

&#13;
&#13;
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;
&#13;
&#13;

您可以在一行中执行此操作:

&#13;
&#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;
&#13;
&#13;

没有箭头功能。

&#13;
&#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;
&#13;
&#13;

答案 1 :(得分:1)

鉴于 colors cars 数组,您可以按以下方式过滤颜色

&#13;
&#13;
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;
&#13;
&#13;

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

&#13;
&#13;
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;
&#13;
&#13;