假设我们有两个这样的对象数组-
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"}];
我们需要编写一个JavaScript函数,该函数分别采用两个这样的数组作为第一个和第二个参数。
然后,该函数应仅从第一个数组(数据数组)中选择那些包含第二个数组(过滤器数组)中所有键值对的对象。
函数应该将所有这些对象推入一个新对象并返回该对象。
对于上面的数组,返回的数组应恰好包含两个这样的对象-
const output = [ {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"}, {"XD_A":"XDR","XD_B_1":"38","XD_B_2":"PB"} ];
为此的代码将是-
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));
输出结果
控制台中的输出将是-
[ { XD_A: 'XDR', XD_B_1: '38', XD_B_2: 'PB' }, { XD_A: 'XDR', XD_B_1: '38', XD_B_2: 'PB' } ]