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.
where array identifies the source data, include identifies the value(s) you want to see in the filtered data set, and the optional if_empty specifies the value to display when the result is an empty set. You can use FILTER() to return a single column or several.
To filter an array of objects based on a property:Use the Array. find() method to iterate over the array. On each iteration, check if the object's property points to the specific value. The find() method will return the first object that satisfies the condition.
To filter a data in an array formula (to exclude or require certain values), you can use an array formula based on the IF, MATCH, and ISNUMBER functions. where "data" is the named range B4:D11 and "filter" is the named range F4:F6. Note: this is an array formula and must be entered with control + shift + enter.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With