How to assign an object property value as a key in the same object?

Issue

Is there a way to assign a value of an object property as a key in the same object?

Like this:

var o = {}
o = {
    a: 111,
    b: 222,
    [o.a]: 'Bingo'
};

This code is wrong because the result is

{a: 111, b: 222, undefined: 'Bingo'}

Solution

You have to do it in two steps

var o = {
    a: 111,
    b: 222
};
o[o.a] = 'Bingo';

console.log (o);

Alternatively, store 111 in a variable first

var x = 111;
var o = {
    a: x,
    b: 222,
    [x]: 'Bingo'
};

console.log (o);

Answered By – flappix

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published