【发布时间】:2019-03-21 22:54:59
【问题描述】:
我的 JSON 如下所示:
{
id: 1,
type: "Sword",
name: "ABC",
description: 'ABC',
rarities: [
{
rarity: 'Common',
damage: 100
},
{
rarity: 'Uncommon',
damage: 200
},
{
rarity: 'Rare',
damage: 300
}
]
}...
以及以下过滤代码:
const string = "Search query";
const keys = ['type', 'name', 'rarity'];
this.setState({
data: data.filter(entry => keys.some(k => entry[k]
.toString()
.toLowerCase()
.includes(string)
))
})
这不起作用并显示Cannot read property 'toString' of undefined。如果我删除 'rarities' 键,它会起作用,但我也无法让它根据 rarities 数组中的对象进行过滤。这个想法是用户应该能够搜索和过滤一个表,其中稀有度中的类型、名称或稀有度等于输入的搜索值。有人知道我应该做什么吗,我需要对数组中的对象进行额外的筛选吗?
【问题讨论】:
-
rarity不是entry对象的属性。 -
首先,你在一行代码中做的太多了。您应该通过将中间步骤分配给变量来将代码分成多行。然后你可以调试你的代码来看看发生了什么。
-
它不是 JSON - 它是一个 JavaScript 对象。
标签: javascript reactjs