Filter array based on dynamic parameter

元气小坏坏 提交于 2021-02-07 13:20:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!