[英]Filtering a JSON with Javascript
我正在尝试使用过滤器过滤 JSON 并且我没有让 clubProducts 像我希望的那样返回(allProducts 工作正常)。 任何帮助表示赞赏。 谢谢
const state = {
added: [],
all: [
{
id: 'bcd755a6-9a19-94e1-0a5d-426c0303454f',
name: 'Iced Coffee',
description: 'Coffee, now featuring ice.',
image: 'https://images.com',
price: 899,
fxCategory: 'Coffee'
},
{
id: 'cc919e21-9a19-94e1-ace9-426c0303454f',
name: 'The 2ndItem',
description: 'Wouldn't you like to know.',
image: 'https://images.com',
price: 499,
fxCategory: 'Club'
}
]
}
const getters = {
allProducts: state => state.all,
clubProducts: state => function () {
return state.all.filter(item => item.fxCategory == 'Club')
}
}
编辑:根据建议更新最新尝试
您犯了两个错误:您只能在数组上使用filter()
(即state.all
在您的情况下),并且在您的比较中您没有引用字符串“Club”。
此外,您的filter()
可以用更短的方式编写,例如:
clubProducts: state.all.filter(item => item.fxCategory == 'Club')
有关更多信息,请参阅文档。
正如@Reydy 提到的,您可以直接在“clubProducts”字段中调用过滤器 function,这个例子是有效的。
但是您可能会收到错误,因为您在“描述”字段中使用了单引号。
试试 state.all
description: "Wouldn't you like to know.",
代替
description: 'Wouldn't you like to know.',
这是我在尝试重复您的示例时遇到错误的唯一地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.