Skip to content
Advertisement

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

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'}

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement