gpt4 book ai didi

javascript - 如果在另一个列表中找到特定属性,则从列表中删除元素

转载 作者:行者123 更新时间:2023-11-30 14:43:51 26 4
gpt4 key购买 nike

我有两个主要包含不同属性的对象列表。但是,它们之间的一个属性是相似的。我正在使用它来验证一个列表不包含具有在另一个列表中找到的对象中存在的属性的对象。

假设 childrenA 是包含属性 nameageweight 的对象列表childrenB 是包含属性 nameeyeColorhairColor 的对象列表。

要过滤 childrenA 使其不包含与 childrenB 中的对象同名的对象,我这样做:

childrenA = childrenA.filter(function(childA) {
return childrenB.some(function(childB) {
return childA.name !== childB.name;
});
});

然而,childrenA 仍然共享 childrenB 的名称。在这种情况下使用 filter/some 是否不正确?

最佳答案

是的,因为如果 任何 元素的回调为真,.some 将返回真,所以只有 childrenB 的一个成员不具有相同的名称(这不是您想要的)。

考虑改用相关的 .every 方法:

(用简单的英语来说,这会检查 childrenB每个成员的名称是否与 childA 不同):

childrenA = childrenA.filter(function(childA) {
return childrenB.every(function(childB) {
return childA.name !== childB.name;
});
});

或者,您可以否定 .some 的返回并改为检查名称相等性:

(同样,在英语中,这会检查childrenB 中是否有不是某些 成员与childA 同名。你应该是能够看出这只是上面相同检查的不同形式)

childrenA = childrenA.filter(function(childA) {
return !childrenB.some(function(childB) { // <-- note the negation
return childA.name === childB.name; // <-- note the ===
});
});

关于javascript - 如果在另一个列表中找到特定属性,则从列表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49264199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com