Suppose, we have two arrays of objects like these −
const data = [ {"XD_A":"XDL","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"51","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"58","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"76","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"} ]; const filters =[{"XD_A":"XDR"},{"XD_B_1":"38"}];
We are required to write a JavaScript function that takes in two such arrays as first and second argument respectively.
Then the function should pick only those objects from the first array (data array) that contains all those key-value pairs that exist in the second array (filter array).
And the function should shove all those objects into a new object and return that object.
For the above array, the returned array should contain exactly two objects like this −
const output = [ {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"} ];
Example
The code for this will be −
const data = [ {"XD_A":"XDL","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"51","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"58","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDL","XD_B_1":"76","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"} ]; const filters =[{"XD_A":"XDR"},{"XD_B_1":"38"}]; const filter = (data, filters) => { return data.filter(e => { try{ filters.forEach(o => { Object.keys(o).forEach(key => { if(e[key] !== o[key]) throw new 1; }); }); return true; } catch(e){ return false; } }); } console.info(filter(data, filters));
Output
And the output in the console will be -
[ { XD_A: 'XDR', XD_B_1: '38', XD_B_2: 'PB' }, { XD_A: 'XDR', XD_B_1: '38', XD_B_2: 'PB' } ]