简体   繁体   English

用 Javascript 过滤 JSON

[英]Filtering a JSON with Javascript

I am trying to filter a JSON using filter and I'm not getting the clubProducts to return as I hoped (allProducts works fine).我正在尝试使用过滤器过滤 JSON 并且我没有让 clubProducts 像我希望的那样返回(allProducts 工作正常)。 Any help is appreciated.任何帮助表示赞赏。 Thank you谢谢

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')
    }
}

EDIT: Updated with latest attempt as per suggestions编辑:根据建议更新最新尝试

You made two mistakes: you can use filter() only on an array (ie state.all in your case), and in your comparison you didn't quote the string 'Club'.您犯了两个错误:您只能在数组上使用filter() (即state.all在您的情况下),并且在您的比较中您没有引用字符串“Club”。

Also, your filter() can be written in a shorter way, as such:此外,您的filter()可以用更短的方式编写,例如:

clubProducts: state.all.filter(item => item.fxCategory == 'Club')

See documentation for more.有关更多信息,请参阅文档

As mentioned by @Reyedy you can call filter function directly in 'clubProducts' field and this example is works.正如@Reydy 提到的,您可以直接在“clubProducts”字段中调用过滤器 function,这个例子是有效的。

But you may get an error because you use single quotes in 'description' field.但是您可能会收到错误,因为您在“描述”字段中使用了单引号。

Try in state.all试试 state.all

description: "Wouldn't you like to know.",

instead of代替

description: 'Wouldn't you like to know.',

This is the only place I got an error trying to repeat your example.这是我在尝试重复您的示例时遇到错误的唯一地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM