-2

I am trying to filter a JSON using filter and I'm not getting the clubProducts to return as I hoped (allProducts works fine). 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

majordomo
  • 1,160
  • 1
  • 15
  • 34
  • 2
    You forgot to quote `'Club'` in your comparison. And it should be `state.all.filter()`. And there's no need to wrap that `filter()` expression in a function. – Robby Cornelissen Apr 03 '20 at 06:45
  • It's a pain to filter a string, maybe filtering an object would help? – Teemu Apr 03 '20 at 06:49
  • Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Reyedy Apr 03 '20 at 06:53
  • As it was noted, `state => function () {` is likely a mistake. Since you didn't provide https://stackoverflow.com/help/mcve that shows how the function is used, this is guesswork. – Estus Flask Apr 03 '20 at 08:10

2 Answers2

1

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'.

Also, your filter() can be written in a shorter way, as such:

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

See documentation for more.

Reyedy
  • 918
  • 2
  • 13
  • 36
  • Thanks Reyedy. I tried with your suggestions and I'm still not getting anything returned. But using allProducts, I get the expected response. – majordomo Apr 03 '20 at 07:09
0

As mentioned by @Reyedy you can call filter function directly in 'clubProducts' field and this example is works.

But you may get an error because you use single quotes in 'description' field.

Try in 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.

aopanasenko
  • 460
  • 3
  • 13