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

Time:05-20

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

CodePudding user response:

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

  • Related