'Is there a way to set the value of one key as the same as the value of another key in the same object in JS?

I want to know if there is a way to access the value of a key to add as the value of another key in the same object.

For example I want:

obj = {key1: 'apple', key2: 'applesauce'};

I tried obj = {key1: 'apple', key2: this.key1 + 'sauce'}

Also tried obj = {key1: 'apple', key2: key1 + 'sauce'}

I want it so that updating key1 automatically updates key2.

Thanks



Solution 1:[1]

You can do it with a getter.

obj = {
  key1: 'apple',
  get key2() {
    return this.key1 + 'sauce';
  }
}

console.log(obj.key2);
obj.key1 = 'awesome';
console.log(obj.key2);

Solution 2:[2]

Basically, not at declaration, not that I know of. You can't refer to the object inside what is basically an object literal using this until the thing actually exists.

You could create a function to generate that object:

function keymaker(key) {
  return {
    key1: key,
    key2: key + 'sauce'
  }
}

obj = keymaker('apple');

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 Barmar
Solution 2 artlung