/ / JavaScript | AngularJS: raccolta dei filtri per valore nidificato: javascript, angularjs, collections, filter, nested

JavaScript | AngularJS: raccolta filtri per valore nidificato: javascript, angularjs, collections, filter, nested

Filtra raccolta per elemento nidificato in matrice

Dì che c'è una collezione:

[ { key: "", param: "", array: ["a", "b", "c"] },... ]

Utilizzo di [Angolare] $filter("filter"), come posso restituire una collezione di oggetti di cui .array contiene il valore specificato "c"?

Ad esempio, si potrebbe immaginare di scrivere quanto segue.

var token = "c";
var query = { array: token };
var anyWithC = filter(collection, query, true);

Non sembra funzionare così ho provato ...

var query = { array: [token] };

Non penso che funzioni neanche.

Qualcuno potrebbe mettermi dritto su questo? È possibile filtrare in questo modo? Devo usare a function invece di un oggetto query?

risposte:

0 per risposta № 1

Uso Underscore library "s _filter (elenco, predicato);

Lavoro dimostrazione

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 per risposta № 2

Puoi usare lodash https://lodash.com/docs

Ho creato un JSFiddle usando angular e lodash: https://jsfiddle.net/41rvv8o8/

Questo è basato sui dati che hai fornito, e questa demo non è case sensitive (maiuscole e minuscole).

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);
}
}
});

Spero che questo ti aiuti!