[英]How in Javascript to esxclude from an Array of Objects the items which contain specific pair of keys and values
I created this snippet to understand the issue我创建了这个片段来理解这个问题
I'm trying with a filter to exclude from an array all the items which have 2 specific keys as value === 'True'
and team === 'Avengers'
.我正在尝试使用过滤器从数组中排除所有具有 2 个特定键作为
value === 'True'
和team === 'Avengers'
项目。
characters.filter(character => character.team !== 'Avengers' && character.value !== 'True');
My goal is to see as a result the following Object我的目标是看到以下 Object
[{
name: "Flash",
team: "Justice League",
value: "False"
}, {
name: "Deadpool",
team: "X-Force",
value: "False"
}]
As you see I should not see any item which has value === 'True'
and also all the items which have team === 'Avengers'
如您所见,我不应该看到任何具有
value === 'True'
的项目以及所有具有team === 'Avengers'
的项目
But from the fiddles, you see that I'm having a wrong result and I don't know how to fix this as there are 2 items that should be excluded because they have value === true
but are not as you see below但是从小提琴中,您会看到我的结果错误并且我不知道如何解决这个问题,因为有 2 个项目应该被排除,因为它们具有
value === true
但不是如下所示
[{
name: "Flash",
team: "Justice League",
value: "False"
}, {
name: "Deadpool",
team: "X-Force",
value: "False"
}, {
name: "Deadpool",
team: "X-Force",
value: "true"
}, {
name: "Deadpool",
team: "X-Force",
value: "true"
}]
String comparison is case-sensitive: a string that equals 'True'
is not a string that equals 'true'
.字符串比较区分大小写:等于
'True'
的字符串不是等于'true'
的字符串。
You can fix this by including both in your filter condition:您可以通过在过滤条件中包含两者来解决此问题:
character.team.== 'Avengers' && character.value !== 'True' && character.value !== 'true'
or (what I would probably do since it's more durable) convert the string to upper-case before comparing for a case-insensitive comparison:或(我可能会这样做,因为它更耐用)在比较不区分大小写的比较之前将字符串转换为大写:
character.team.toUpperCase().== 'AVENGERS' && character.value.toUpperCase() !== 'TRUE'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.