Weronika
Weronika

Reputation: 330

How to reference to element from state in foreach (Vuex)?

I am using vuex in my vue application. In store is a declared object:

    state: {
        list: {
            a: false,
            b: false,
            c: false
        }
    }

In mutations is mutation that receives arrays in parameters, for example: el: ['a', 'b']. Those elements in the el array must be set to true in list object in state. I'm using a foreach loop for this:

    mutations: {
        SET_LIST(state, el) {
            el.forEach(element => {
                if (state.list.element) {
                    state.list.element = true;
                }
            });
        }
    }

But I am getting an error: error 'element' is defined but never used. Because element is not used and I don't know how to refer to it correctly.

I searched on the internet and found this solution: state.list[element]. I don't get an error then, but it doesn't work.

Upvotes: 2

Views: 752

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Use the bracket notation [] to get the property dynamically :

   mutations: {
        SET_LIST(state, el) {
            el.forEach(element => {
                if (Object.keys(state.list).includes(element)) {
                    state.list[element] = true;
                }
            });
        }
    }

Upvotes: 3

Related Questions