Filtrovať zbierku podľa vnorených položiek v poli
Povedzme, že existuje zbierka:
[ { key: "", param: "", array: ["a", "b", "c"] },... ]
Použitie [Angular] $filter("filter")
, ako môžem vrátiť kolekciu objektov, ktorých .array
obsahuje zadanú hodnotu "c"
?
Dalo by sa napríklad predstaviť, že napíšete nasledujúce.
var token = "c";
var query = { array: token };
var anyWithC = filter(collection, query, true);
Zdá sa, že to nefunguje, takže som sa pokúsil ...
var query = { array: [token] };
Ani si nemyslím, že to funguje.
Mohol by ma niekto postaviť priamo na tento? Je to možné takto filtrovať? Musím použiť a function
namiesto objektu dopytu?
odpovede:
0 pre odpoveď č. 1použitie Podčiarknutie knižnice _.filter (zoznam, predikát);
pracovné demonštrácie
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 pre odpoveď č. 2
Môžete použiť lodash https://lodash.com/docs
Vytvorili sme JSFiddle pomocou uhla a lomka: https://jsfiddle.net/41rvv8o8/
Vychádza to z údajov, ktoré ste poskytli, a toto demo nerozlišuje veľké a malé písmená (veľké a malé písmená).
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);
}
}
});
Dúfam, že to pomôže!