user1701840
user1701840

Reputation: 1112

How to dynamically create obj property in javascript?

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 ?

Upvotes: 0

Views: 41

Answers (2)

Roco CTZ
Roco CTZ

Reputation: 1117

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.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

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';

Upvotes: 1

Related Questions