筛选和排序对象



输入数据示例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();

过滤条件也可以是";包括";或";排除";。我只有一个想法如果像这样的语句

if (include) {
array.filter(e => e.xxx === condition.xxx)
} else {
array.filter(e => e.xxx !== condition.xxx)
}

请帮助理解实现的逻辑。

这将适用于多个include和多个sort_by选项。

在进行比较时,我假设所有值都是字符串。您可以根据需要进行扩展。

const input = {
data: [
{ name: "Kyle", code: "ASDF", email: "kyle1@mail.com", web: "kyle.com" },
{ name: "Kyle", code: "ASDF", email: "kyle1@mail.com", web: "kyle.au" },
{ name: "Kate", code: "notASDF", email: "kate@mail.com" },
],
};
const rule = {
condition: {
include: [{ name: "Kyle" }, { code: "ASDF" }],
sort_by: ["email", "web"],
},
};
const output = input.data
.filter((item) =>
rule.condition.include.every((obj) =>
Object.entries(obj).reduce(
(cond, [key, value]) => cond && item[key]?.includes(value),
true
)
)
)
.sort((a, b) =>
rule.condition.sort_by
.map((key) => a[key].localeCompare(b[key]))
.reduce((prev, curr) => prev || curr, 0)
);
console.log(output);

使用Object.entries()、Array.prototype.every()、Array.protype.reduce()和Array.prototype.filter()

当输入和规则在同一个文件中时,它可以工作。但当我拿到它们时,我得到了一个错误

"未捕获(承诺中)类型错误:项[key]?。includes不是函数";

无法理解这一点。获取后,输入对象和规则对象完全相同。

const input = {
data: [],
};
const rule = {};
async function fetchAsync() {
const response = await fetch("./input.json");
const data = await response.json();
data.data.forEach((item) => {
input.data.push(item);
});
rule.condition = data.condition;
console.log(input);
console.log(rule);
const output = input.data
.filter((item) =>
rule.condition.include.every((obj) =>
Object.entries(obj).reduce(
(cond, [key, value]) => cond && item[key]?.includes(value),
true
)
)
)
.sort((a, b) =>
rule.condition.sort_by
.map((key) => a[key].localeCompare(b[key]))
.reduce((prev, curr) => prev || curr, 0)
);
console.log(output);
}
fetchAsync();

最新更新