9

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.

0

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3

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

Comments

2
function getFilteredCodes(poolArray,key,val){
    return poolArray.filter(function(item,ind){
        return item[key]==val;
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.