Access value of object key in the same object

Viewed 63

Is there any way to access the value of a key of an object in the same object?

Something like this:

const myObj = {
    keyOne: 'value',
    keyTwo: this.keyOne + 'another value'
})

I know that this may be a previously asked question, but I didn't found any answer to this problem.

2 Answers

You can use a getter:

const myObj = {
    keyOne: 'value',
    get keyTwo() { return this.keyOne + 'another value' }
};

console.log(myObj);

const myObj = {
    keyOne: 'value',
};
myObj.keyTwo = myObj.keyOne + " an custom text";

console.log(myObj);

Related