问题
Say I have an array of json objects which looks like below:
var codes = [{
"code_id": "1",
"code_name": "code 1", ,
}, {
"code_id": "2",
"code_name": "code889",
},
// ... () ...
]
How can I filter codes array based on dynamic input parameter?
So I am looking for a generic function which will take input array and key and value as i/p.
var filteredCodes = getFilteredCodes(codes, "code_id", 2);
Thanks.
回答1:
Use Array.prototype.filter
to filter out the result - see demo below:
var codes = [{"code_id": "1","code_name": "code 1"}, {"code_id": "2","code_name": "code889"}];
function getFilteredCodes(array, key, value) {
return array.filter(function(e) {
return e[key] == value;
});
}
var filteredCodes = getFilteredCodes(codes, "code_id", 2);
console.log(filteredCodes);
回答2:
You could use Array#filter with the key and value.
function getFilteredCodes(array, key, value) {
return array.filter(function (o) {
return o[key] === value;
});
}
var codes = [{ "code_id": "1", "code_name": "code 1", }, { "code_id": "2", "code_name": "code889" }],
filteredCodes = getFilteredCodes(codes, "code_id", "2");
console.log(filteredCodes);
回答3:
function getFilteredCodes(poolArray,key,val){
return poolArray.filter(function(item,ind){
return item[key]==val;
});
}
回答4:
Or the function in an only line with arrow notation
var codes = [{ "code_id": "1", "code_name": "code 1", }, { "code_id": "2", "code_name": "code889" }];
var getFilteredCodes = (array, key, value) => array.filter(x => x[key] === value);
var FilteredCodes = getFilteredCodes(codes, "code_id", "2");
console.log(FilteredCodes);
来源:https://stackoverflow.com/questions/41227452/filter-array-based-on-dynamic-parameter