我有一个JSON对象如下:
let data = [{"grade":"A","batch":"night", "rating":5}, {"grade":"B", "batch":"morning", "rating":6},
{"grade":"C", "batch":"night", "rating":7},
{"grade":"A", "batch":"morning", "rating":8}]
我想在名为“grade”和“batch”
的对象的两个属性上过滤json我怎样才能在javascript中执行此操作?
答案 0 :(得分:0)
以下是示例代码。您可以添加过滤器对象,以便过滤和运行代码。结果将显示在窗口的控制台中。
您可以尝试运行输出的代码段
function multiFilter(array, filters){
const filterKeys = Object.keys(filters);
// filters all elements passing the criteria
return array.filter((item) => {
// dynamically validate all filter criteria
return filterKeys.every(key => !!~filters[key].indexOf(item[key]));
});
}
let data = [{"grade":"A","batch":"night", "rating":5}, {"grade":"B", "batch":"morning", "rating":6},
{"grade":"C", "batch":"night", "rating":7},
{"grade":"A", "batch":"morning", "rating":8}]
let filters = {
"grade" : ["A", "B"],
"batch" : ["morning"]
};
let filtered = multiFilter(data, filters);
console.log(filtered);