Is there a way to assign a value of an object property as a key in the same object?
Like this:
JavaScript
x
7
1
var o = {}
2
o = {
3
a: 111,
4
b: 222,
5
[o.a]: 'Bingo'
6
};
7
This code is wrong because the result is
{a: 111, b: 222, undefined: 'Bingo'}
Advertisement
Answer
You have to do it in two steps
JavaScript
1
7
1
var o = {
2
a: 111,
3
b: 222
4
};
5
o[o.a] = 'Bingo';
6
7
console.log (o);
Alternatively, store 111 in a variable first
JavaScript
1
8
1
var x = 111;
2
var o = {
3
a: x,
4
b: 222,
5
[x]: 'Bingo'
6
};
7
8
console.log (o);