user8870654
user8870654

Reputation:

Get object from array with Vuex getter

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?

Upvotes: 2

Views: 4241

Answers (1)

ittus
ittus

Reputation: 22393

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

Upvotes: 4

Related Questions