[Vuejs]-Find object in state by id, if object found do something, if object not found do something else

2👍

SOLVED

I used the .some() method to solve the problem.

Here’s the code I used:

SET_SHIPPING_FEES: (state, payload) => {
   if (state.shippingFees.length > 0) {
     const shippingFeeDoesExist = state.shippingFees.some(fee => fee.id === 
     payload.id);

     if (shippingFeeDoesExist) {
      for (let i = 0; i < state.shippingFees.length; i += 1) {
        if (state.shippingFees[i].id === payload.id) {
          state.shippingFees.splice(i, 1, payload);
        }
      }
    } else {
      state.shippingFees.push(payload);
    }
  } else {
    state.shippingFees.push(payload);
  }
},

Leave a comment