1

I need to do this :

let obj = {}
obj.obj1 =  {'obj11':5}
console.log(obj.obj1.obj11)

//5

but I need to define the last key of the last object dynamically for example, something like this:

let obj = {}
key = 'obj11'
obj.obj1 =  { key :5}
console.log(obj.obj1.obj11)
// undefined
Muhammad Usman
  • 10,039
  • 22
  • 39

4 Answers4

1

To define computed properties in javascript objects use [].

Try the following:

let obj = {}
key = 'obj11'
obj.obj1 =  { [key] :5}
console.log(obj.obj1.obj11)

For reference : Reference

amrender singh
  • 7,949
  • 3
  • 22
  • 28
1

Try

obj.obj1[key] = 5;

console.log(obj.obj1.obj11);

The object notation syntax does not support variables as keys directly, but java-script dictionaries do.

To evaluate the variable in the object notation syntax, use a bracket like so

obj.obj1 = {[key]: 5};

console.log(obj.obj1.obj11);
Dan
  • 1,812
  • 3
  • 13
  • 27
0

You'll have to use bracket notation for this like

let obj = {}
key = 'obj11'
obj.obj1 =  { [key] :5}
console.log(obj.obj1.obj11)
Muhammad Usman
  • 10,039
  • 22
  • 39
-1

Yes, you can do this:

console.log(obj.obj1[key]);

Every object in JavaScript is basically a dictionary so you can access it via the dictionary syntax.

Keveloper
  • 773
  • 5
  • 10