0

I want to create a JSON like this:

{
   '2014-1-1':
             {
             'objA':
                   {
                        'attrA': 'A'
                        'attrB': 'B'
                   }
             }

}

I tried:

  obj['2014-1-1'] = {'objA' : { 'attrA' : 'A'}};

  obj['2014-1-1'] = {'objA' : { 'attrB' : 'B'}};

But I only see B value on my object now, I guess 'because 'objA' is being overridden, how do I add 'attrA' and 'attrB' both for objA ?

2 Answers 2

1

Once the property exists, simply access it and set a value, don't overwrite:

obj['2014-1-1'] = {'objA' : { 'attrA' : 'A'}};
obj['2014-1-1']['objA']['attrB'] = 'B';

You'd probably just want to make a check to see if the property exists, if not, create it, then assign:

if (!obj['2014-1-1'].hasOwnProperty('objA')) {
    obj['2014-1-1']['objA'] = {}
}

obj['2014-1-1']['objA']['attrA'] = 'A';
obj['2014-1-1']['objA']['attrB'] = 'B';
Sign up to request clarification or add additional context in comments.

3 Comments

what if I don't know if 'objA' exist?
Use the hasOwnProperty method to check for existence: if (obj['2014-1-1'].hasOwnProperty('objA'))
@user1701840 You make a check?
0

It's not working because you are overwriting the object. You can do it like this:

obj['2014-1-1'] = {'objA' : { 'attrA' : 'A', 'attrB' : 'B'}};

attrA and attrB are two different properties of objA so this way you set both of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.