2

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, find() in this scenario is a perfect sweet and short answer to the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.