Why can not I create two sub-levels within an object?

0
var objeto = {
   sub1_A: {},
   sub1_B: {},
   sub1_C: {}
}

I have no problems if I do the following:

objeto.sub1_A.sub2 = "Prueba";

But yes if I descend a level more directly:

objeto.sub1_A.sub2.sub3 = "Prueba";

If I try to set the above, it says "Uncaught TypeError: Can not set property 'recodes' of undefined." I understand that it is because you can set / define a method or property of an existing object but not one that does not.

Is not there a way to go down as many levels as you want by creating that "way"?

If I wanted to create something like object.sub1.sub2.sub3.sub4.sub5="SetealoYa!" Am I forced to go step by step? I am convinced that there must be another method.

Thank you very much in advance!

    
asked by Adrià Fàbrega 28.08.2018 в 15:39
source

1 answer

3

You can do it with objeto.sub1_A.sub2 = "Prueba"; since sub1_A is an object, this object you defined in your main object

var objeto = {
   sub1_A: {},// aquí definiste sub1_A como objeto
   sub1_B: {},
   sub1_C: {}
}

When you define sub2 , you are defining that sub1_A has a property of type string called sub2 whose value is test.

Doing objeto.sub1_A.sub2.sub3 = "Prueba"; marks you error Uncaught TypeError: Cannot set property 'recodes' of undefined because there is no property of sub1_A that is sub2.

This property would have to be an object so that it could have another property. Then you could do the following.

objeto.sub1_A.sub2 = {};
objeto.sub1_A.sub2.sub3 = "prueba"

If you would like to add one more level, you would have to convert sub3 to object, since you can not add properties to a string.

    
answered by 28.08.2018 / 16:15
source