Search code examples
arrayspushvuexmutation

Vuex state.array.push adds objects inside of array row


I develop filter functionality and after pushing array Vuex pushes all objects of array inside one array row.

pushFiltered (state, payload) {  
    state.filtered.push(payload)
},

This is result on vue dev tools:

filtered:Array[3]
0:Object
1:Object
2:Array[2]
  >0:Object
  >1:Object

How to extract and push correctly? Also spread operator, concat too not helps.

UPDATE: I found solution. If there is a single object and you want to push whole object into an array then no need to iterate the object. from stackoverflow

This is my solution:

pushFiltered (state, payload) {
        payload.forEach(function(row) {
          state.filtered.push(row)
        });
    }

It works but i don't know is good practice or not


Solution

  • Based on your code, I guess the first time filtered is not an array, I mean the initial state in the store.

    So if you are passing and array of objects and want to push them, you can do it this way:

    The initial state of filtered:

    ...
    filtered: [],
    ...
    

    The mutation:

    mergeFiltered (state, payload) {
        state.filtered = [...state.filtered, ...payload]
    }
    

    That way you are doing a merge between the current values in the filtered array and the incoming payload.