Reputation: 375
I have an response as a json array with lots of records but i want to filter that json array by using another json array.
my json response
and my filter json array be like
"filterParams" : [
{
"param" : "actualSum",
"value" : "95",
"type" : "text",
"comparision" : "isEqual"
},
{
"param" : "wbsSort",
"value" : "6",
"type" : "text",
"comparision" : "isEqual"
}
],
so how can i filter my response using javascript or node js anything. i want to get filtered data like match param with reponse param and its value.
e.g. if there is match value of actualSum with 95 and wbsSort's value equal to 6 then it will return true other wise false.
Upvotes: 1
Views: 1974
Reputation: 1917
A way to do this without having to hardcode every check would be to create a compare function using the filterParams
. So you would do something like this, where compareFunction
creates a new function using filterParams
to initialize the variables to check and returns whether the current item has these values. So for any further check you want to do, you will only have to add it to filterParams. Hope this helps.
const filterParams = [{
"param" : "actualSum",
"value" : "95",
"type" : "text",
"comparison" : "isEqual"
}, {
"param" : "wbsSort",
"value" : "6",
"type" : "text",
"comparison" : "isEqual"
}];
const data = [{ actualSum: 95, wbsSort: 6 }, { actualSum: 95, wbsSort: 10 }];
const operators = {
'isEqual': '==='
};
const compareFunction = (params) =>
(item) => new Function(
params.reduce((acc, { param, value }) => `${acc} const ${param} = ${value};`, '') +
params.reduce((acc, { param, value, comparison }, i) => `${acc} ${param} ${operators[comparison]} ${item[param]} ${i !== params.length - 1 ? '&&' : ';'}`, 'return ')
)();
const filteredData = data.filter(compareFunction(filterParams));
console.log(filteredData);
Upvotes: 0
Reputation: 5967
You could filter the items in the result array where the item matches every parameter in filterParams
. If you only want to check if at least one match exists replace .filter
with .some
e.g.
var matches = results.filter(item =>
filterParams.every(paramItem =>
item[paramItem.param] === paramItem.value));
I've limited it to equals comparison but you can expand the comparison using a switch
based on the other comparison types you have.
Upvotes: 2