输入数据示例json文件:
{"data": [{"name": "Kyle", "email": "kyle2@mail.com"},
{"name": "Kyle", "email": "kyle1@mail.com"},
{"name": "Kate", "email": "kate@mail.com"}]}
筛选和排序条件示例json文件:
{"condition": {"include": [{"name": "Kyle"}], "sort_by": ["email"]}}
结果:
{"result": [{"name": "Kyle", "email": "kyle1@mail.com"},
{"name": "Kyle", "email": "kyle2@mail.com"}]}
逻辑应该是什么?.filter和.sort是处理此任务的最佳方式吗?
const array = [];
const filterCondition = {}
async function fetchAsync() {
const response = await fetch("./input.json");
const data = await response.json();
// get array to work with
data.data.forEach((item) => {
array.push(item);
});
// here I tried to get condition to the variable, so later I can use .filter method
const filterCondition = data.condition.exclude[0];
// I understand that this is bad way... And you could also have more than one condition in that array..
// But how can you access that condition in the json condition file?
}
fetchAsync();
另外,过滤条件可以是“include”或“exclude”。我只想做这样的if语句
if (include) {
array.filter(e => e.xxx === condition.xxx)
} else {
array.filter(e => e.xxx !== condition.xxx)
}
请帮助我们了解自觉的逻辑。
2条答案
按热度按时间rqqzpn5f1#
这将适用于多个
include
和多个sort_by
选项。我假设所有的值在比较时都是字符串。你可以根据需要扩展它。
使用Object.entries()、Array.prototype.every()、Array.prototype.reduce()和Array.prototype.filter()
a6b3iqyw2#
当输入和规则在同一个文件中时,它可以工作,但是当我获取它们时,我得到了一个错误
“未捕获(承诺中)类型错误:项[键]?.includes不是函数”
无法理解。输入和规则对象在提取后完全相同。