manipulating JSON JS

Asked

Viewed 55 times

0

I want to know why it works to change but not to create

    var obj = {};
    
    obj.teste = {id:1}; //esse funciona para criar
    
    obj.teste.id = 2; //e assim eu altero
    
    console.log(JSON.stringify(obj)); 
    
    
    var obj2 = {};
    obj2.teste2.id = 1; //isso não funciona, e pra mim faria sentido que o js criasse um obj com o id, mas ele da erro Cannot set property 'id' of undefined
    
    onsole.log(JSON.stringify(obj2));

I want to understand the point where my intuition says example 2 should work, but it doesn’t work.

  • 3

    How come it doesn’t work to create? What exactly are you trying to do?

  • 1

    edited the publication

1 answer

3


So, man. When you try to access add a value to obj.teste.id an error occurs because the id parent that is obj.teste is only a variable and not a dictionary, these are initialized with {}. Dictionary or objects can hold a text value as a key. Example:

obj.teste = {}    
obj.teste.id = 3;
obj.teste.indice1 = 4;
obj.teste.valorBool = true;

However, you can only do something of this kind after the variable has received the dictionary value, which in the above code is shown as obj.teste = {}. Therefore the {} is used to initialize the dictionary, so all values are overwritten when you try to use obj.teste = {id:1};, this only serves to initialize. To change you can use the obj.teste.id = 1;

In the case of obj2 an error occurs because obj2 received a dictionary but attribute obj2.teste2 no, it’s just a variable.

  • I think I got it, like, you have to explain where the dictionary starts

  • yeah, basically that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.