2

Say i have this object:

test = {
    testObj: {
        "1": {
            "key": "value"
        }
    }
}

And i want to add values to testObj like so:

test.testObj["2"].key = "my value";

I get error TypeError: Cannot set property 'key' of undefined

Now i do understand that key does not exist yet, but 2 doesn't exist also, and yet i can set value to it:

test.testObj["2"] = "something";

So what can i do about it?

EDIT wow i feel stupid for not figuring that out by myself... anyways thank you guys.

Linas
  • 4,380
  • 17
  • 69
  • 117
  • Check below link. http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object-literal – Dips Aug 13 '12 at 20:18
  • @Linas don't feel stupid... but _do_ mark an answer. ;) – canon Aug 13 '12 at 20:54

1 Answers1

3

Javascript doesn't know what test.testObj["2"] should be in this scenario, so it ends up testing it as an existing property:

test.testObj["2"].key = "my value";

The assignment can only apply to the last part of the structure on the left.

But you can tell it what it is by creating the object first:

test.testObj["2"]={};
test.testObj["2"].key = "my value";

Or in a single step:

test.testObj["2"] = { key: "my value"};
Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119