我正在尝试返回以下数组中所有破坏关系的项目:
[
{ id: "1", option: { bound_id: "2" }},
{ id: "2", option: { bound_id: "12" }},
{ id: "12", option: { bound_id: "2" }}
]
如您所见,每个项目都使用属性 bound_id
相互链接,如果属性破坏了如下关系:
[
{ id: "1", option: { bound_id: null }},
{ id: "2", option: { bound_id: "12" }},
{ id: "12", option: { bound_id: "2" }}
]
返回结果如下:
[
{ id: "2", option: { bound_id: "12" }}
{ id: "12", option: { bound_id: "2" }}
]
我正在使用以下代码:
const input = [
{ id: "1", option: { bound_id: null }},
{ id: "2", option: { bound_id: "12" }},
{ id: "12", option: { bound_id: "2" }}
];
const output = input.filter(a => a.option.bound_id);
console.log(output);
我想包括的是只插入下一个项目的关系,一个例子更好:
[
{ id: "1", option: { bound_id: "2" }},
{ id: "2", option: { bound_id: "3" }},
{ id: "12", option: { bound_id: "2" }}
]
如您所见,id 为 2
的项目打破了与 id 12
的关系,并指向一个 id 为 3
的项目t 存在于集合中,在这种情况下输出应该是:
[
{ id: "1", option: { bound_id: "2" }},
{ id: "2", option: { bound_id: "3" }}
]
我如何使用过滤器来做到这一点?
最佳答案
在使用 .filter
时,您可以将 id
和 .filter
添加到 Set
通过正在迭代的 bound_id
是否包含在 Set
中(如果没有,将其添加到集合中;如果是,则让项目在 .filter 中失败
测试)。如果索引为 0,也保留该项目,因为您总是希望保留第一条记录:
const input = [
{ id: "1", option: { bound_id: "2" }},
{ id: "2", option: { bound_id: "3" }},
{ id: "12", option: { bound_id: "2" }}
];
const alreadyHave = new Set();
const filtered = input.filter(({ option }, index) => {
const { bound_id } = option;
if (!alreadyHave.has(bound_id) || index === 0) {
alreadyHave.add(bound_id);
return true;
}
});
console.log(filtered);
如果根据评论,您实际上想要始终删除第一项,则将条件更改为&& index !== 0
:
const input = [
{ id: "1", option: { bound_id: "2" }},
{ id: "2", option: { bound_id: "3" }},
{ id: "12", option: { bound_id: "2" }}
];
const alreadyHave = new Set();
const filtered = input.filter(({ option }, index) => {
const { bound_id } = option;
if (!alreadyHave.has(bound_id) && index !== 0) {
alreadyHave.add(bound_id);
return true;
}
});
console.log(filtered);
或者,根据评论,如果第一项的逻辑应该相同,则完全删除 index
条件:
const input = [
{ id: "1", option: { bound_id: "2" }},
{ id: "2", option: { bound_id: "3" }},
{ id: "12", option: { bound_id: "2" }}
];
const alreadyHave = new Set();
const filtered = input.filter(({ option }, index) => {
const { bound_id } = option;
if (!alreadyHave.has(bound_id)) {
alreadyHave.add(bound_id);
return true;
}
});
console.log(filtered);
关于javascript - 使用过滤器时如何设置条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280829/