Filtruj kolekcję według zagnieżdżonego elementu w szyku
Powiedzmy, że jest kolekcja:
[ { key: "", param: "", array: ["a", "b", "c"] },... ]
Korzystanie z [Angular] $filter("filter")
, jak mogę zwrócić kolekcję obiektów, których .array
zawiera określoną wartość "c"
?
Na przykład można sobie wyobrazić napisanie następującego.
var token = "c";
var query = { array: token };
var anyWithC = filter(collection, query, true);
To chyba nie działa, więc próbowałem ...
var query = { array: [token] };
Nie sądzę też, żeby to działało.
Czy ktoś mógłby mnie na to postawić? Czy można to tak filtrować? Czy muszę użyć function
zamiast obiektu zapytania?
Odpowiedzi:
0 dla odpowiedzi № 1Posługiwać się Biblioteka podkreślenia _. filtr (lista, predykat);
Pracujący próbny
var sample = [{
name: "test",
lastName: "test",
address: ["a", "b", "c"]
}, {
name: "test1",
lastName: "test1",
address: ["d", "e", "f"]
}, {
name: "test2",
lastName: "test2",
address: ["g", "h", "i"]
}];
//key is the objecy key from which the value will be extracted to compare with the token.
function filterByKey(list, key, token) {
var filterArray = _.filter(list, function(value) {
//If Undefined value then should return false
if (_.isUndefined(value[key])) {
return false;
} else if (_.isArray(value[key])) {
//Checks the extracted value is an Array
return _.contains(value[key], token);
}else {
return value[key] === token;
}
});
return filterArray;
}
console.log("Output ------------- ", filterByKey(sample, "address", "h"));
0 dla odpowiedzi nr 2
Możesz użyć lodash https://lodash.com/docs
Utworzyłem JSFiddle za pomocą kątownika i lodash: https://jsfiddle.net/41rvv8o8/
Jest to oparte na podanych przez Ciebie danych, aw tym pokazie nie jest rozróżniana wielkość liter (wielkie i małe litery).
HTML
<div ng-app="app">
<example-directive>
</example-directive>
</div>
JavaScript
var app = angular.module("app",[]);
app.directive("exampleDirective", function() {
return {
template:"<h1>Collections with array containing c</h1><ul><li ng-repeat="collection in matchcollections">key: {{collection.key}}, param: {{collection.param}}, <div ng-repeat="item in collection.array">{{item}}</div></li></ul>",
controller: function($scope){
$scope.collections = [ { key: "A", param: "A1", array: ["a", "b", "c"] },{ key: "B", param: "B1", array: ["x", "h", "c"] },{ key: "C", param: "C", array: ["t", "a", "k"] }];
$scope.matchcollections = _.filter($scope.collections, function(c){
return _.includes(c.array,"c")
});
console.log("Collection with match: ", $scope.matchcollections);
}
}
});
Mam nadzieję że to pomoże!