Search code examples
javascriptvue.jsvuex

Find an object in array


I am making a filter that allows user clicks a checkbox to do filter. When I click a checkbox, It will add that object of item into an array of filters. When clicking again that item, I will remove that item from the array.

I am using a hard code for the object of item to make sure they are the same object every time I click. The object look like this:

var item1 = {name: "A", id: 1};

The below toggleFilter method is triggered when I click a checkbox, then dispatch an action from Vuex.

methods: {
            toggleFilter(categoryId) {
                var item1 = {name: "A", id: 1};

                this.$store.dispatch('filter/toggleFilter', item1);
            }
        }

Vuex action:

let actions = {
    toggleFilter({state, commit, rootState, rootGetters}, attribute) {
        let index = state.filters.indexOf(attribute);

        if (index === -1) {
            commit('addFilter', attribute);
        } else {
            commit('removeFilter', index);
        }

        console.log(state.filters);
    }
};

The problem is when I click again the checkbox, it doesn't remove the object from the array, it adds 1 more object into it.

enter image description here

One more weirdness thing is I use the exact above Vuex action for another object, something like this:

methods: {
            toggleFilter(option) {
                option.attributeId = this.attribute.id;
                option.type = 'attribute';

                this.$store.dispatch('filter/toggleFilter', option);
            }
        }

And it works. I don't know why the 1st case doesn't work, but the 2nd case works.


Solution

  • Every time you create new object var item1 = {name: "A", id: 1};, so indexOf can't not find it. If you item's id is unique, you can try comparing attribute.id

    let actions = {
        toggleFilter({state, commit, rootState, rootGetters}, attribute) {
        let index = state.filters.map(item => item.id).indexOf(attribute.id);
            if (index === -1) {
                commit('addFilter', attribute);
            } else {
                commit('removeFilter', index);
            }
    
            console.log(state.filters);
        }
    };