[英]How to filter by array of objects?
My JSON looks like this: 我的JSON看起来像这样:
{
id: 1,
type: "Sword",
name: "ABC",
description: 'ABC',
rarities: [
{
rarity: 'Common',
damage: 100
},
{
rarity: 'Uncommon',
damage: 200
},
{
rarity: 'Rare',
damage: 300
}
]
}...
and the following filtering code: 和以下过滤代码:
const string = "Search query";
const keys = ['type', 'name', 'rarity'];
this.setState({
data: data.filter(entry => keys.some(k => entry[k]
.toString()
.toLowerCase()
.includes(string)
))
})
which doesn't work and says Cannot read property 'toString' of undefined
. 这不起作用,并说Cannot read property 'toString' of undefined
。 It works if I remove the 'rarities'
key but I am unable to get it to filter based on objects in the rarities array too. 它可以工作,如果我删除'rarities'
键但我无法让它过滤基于稀有数组中的对象。 The idea is that the user should be able to search and filter a table where the type, name or rarity inside rarities equals the entered search value. 这个想法是用户应该能够搜索和过滤一个表格,其中稀有内部的类型,名称或稀有度等于输入的搜索值。 Does someone know what im supposed to do, do I need to do additional fintering for objects within the array? 有人知道我应该做什么,我是否需要对数组中的对象进行额外的查找?
This is because when checking for the key rarity: entry[k]
where k = rarity entry[rarity]
, at this point 这是因为在检查密钥稀有时: entry[k]
其中k =稀有entry[rarity]
,此时
keys.some(k => entry[k]
.toString()
.toLowerCase()
.includes(string)
) )
will look like: 看起来像:
keys.some(k => entry['rarity']
.toString()
.toLowerCase()
.includes(string)
) )
entry['rarity']
doesn't exist so its undefined
so basically its trying to do undefined.toString()....
. entry['rarity']
不存在因此它undefined
所以基本上它试图做undefined.toString()....
rarity is nested inside rarities
. 珍稀在rarities
内嵌套。 So to access this you would have to be looking inside entry['rarities']['rarity']
所以要访问这个,你必须要查看entry['rarities']['rarity']
You could try importing lodash https://lodash.com/
and then use lodash's _.get method to have something like : 您可以尝试导入lodash https://lodash.com/
,然后使用lodash的_.get方法来执行以下操作:
const string = "Search query";
const keys = ['type', 'name', 'rarities.rarity'];
this.setState({
data: data.filter(entry => keys.some(k => _.get(entry, k)
.toString()
.toLowerCase()
.includes(string)
))
})
see that for your keys rarity
is now rarities.rarity
this should work 看到你的钥匙rarity
现在是rarities.rarity
这应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.