'How can I change the value of an object by passing in the key as a function argument?

I am trying to change the value of an object key with a function by passing in the object key in order to avoid repetitive code.

I managed to set the value manually within the click event with "object.key = true", but with this method I need to include the other aspects of the desired function each time for every event listener, which I am trying to avoid. So I tried other object methods like "Object.keys(obj)", "Object.value(obj)", "Object.entries(obj)" & "Object.defineProperty(obj, key, value)" which did not conclude my intent.

const object = {
    key1: false,
    key2: false,
    key3: false,
}

const func = (anyKey)=>{
    // method to pass in any key and set value to true
    // inlcuding other unrelated methods
}

button1.addEventListener('click', func(key1));
button2.addEventListener('click', func(key2));
button3.addEventListener('click', func(key3));

To sum it up: I would like to change the value of the keys by passing them as an argument to a function, the methods above that I have tried added keys to the Object. Any input is welcome



Solution 1:[1]

Your code should be working as you expect it, but with the problem that the "func" function will execute on load as well, because you added the () when adding it as a listener. Here is a small snippet which should produce something similar to what you need. I made a toggle button which switches between true and false on key1 when pressed.

const object = {
    "key1": false,
    "key2": false,
    "key3": false,
}

const toggleValue = (anyKey)=>{
    object[anyKey] = !object[anyKey];

   console.log(object);
}

button1 = document.getElementById("button1");

button1.addEventListener('click', function(){
    toggleValue("key1");
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan Iftinca