Search code examples
javascriptvue.jsvuejs2vuex

How to get an item from an array of objects stored in Vuex by ID field?


I have an array of objects in a Vuex store. Like this:

[
  {
    id: 1,
    value: 'some value'
  },
  {
    id: 2,
    value: 'other value'
  },
  ...
]

Is there a way to create a getter to get a certain item of the array by id?

Something like

getArrItem(state, id) {
  return state.find(item => item.id === id);
}

Solution

  • You could use method-style-access as follows :

    getArrItem: (state) => (id) => {
      return state.items.find(item => item.id === id);
    }