Home > other >  Is there a way to set the value of one key as the same as the value of another key in the same objec
Is there a way to set the value of one key as the same as the value of another key in the same objec

Time:04-29

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

CodePudding user response:

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);

CodePudding user response:

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');
  • Related