我试图返回以下数组中破坏了关系的所有项目:
[
{ 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
并指向该ID3
在集合中不存在的项目,在这种情况下,输出应为:
[
{ id: "1", option: { bound_id: "2" }},
{ id: "2", option: { bound_id: "3" }}
]
如何使用过滤器做到这一点?
在使用时.filter
,您可能会添加到的Set
中id
,并.filter
根据是否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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句