2
votes

I have a piece of state that is an array. In a getter I filter it and return an object which matches another piece of state, like this:

selectedItem: state => {
  return state.items.filter(
    item => item.id == state.selectedId
  );
},

However, filter() returns an array, which in this case gives me an array with ONE object, the item with the selectedId. I can add [0] to access this first object in the array, but that's a really ugly hack. Is there any other way to make sure I get an object and not an array when filtering in a Vuex getter?

1

1 Answers

4
votes

You can use find method instead. It will return an object or undefined if can't find matching object

selectedItem: state => {
  return state.items.find(
    item => item.id == state.selectedId
  );
},

Reference