2

This might have been asked before, but I didn't see exactly this question:

Is there a way to declare an object in javascript such that I can directly assign values in multiple levels of nesting (without declaring each level along the way)?

Example:

var obj = {};
obj["key1"]["key2"]["key3"] = "value";
obj["key1"]["key4"]["key5"] = "value2; 

The above doesn't work for me, but since I'm creating the object dynamically, creating each level along the way for each key would be costly as I'd have to check for existence first..

ie:

if (!obj["key1"]) obj["key1"] = {};
elseif (!obj["key1"]["key2"]) !obj["key1"]["key2"] = {};
... etc

I hope that makes sense.

ddnm
  • 187
  • 1
  • 10
  • 1
    Write helper function like `setObj(obj, 'key1.key2.key3', 'value')`. – dfsq May 13 '15 at 21:02
  • possible duplicate of [How to set object property (of object property of..) given its string name in JavaScript?](http://stackoverflow.com/questions/13719593/how-to-set-object-property-of-object-property-of-given-its-string-name-in-ja) – just-boris May 13 '15 at 21:05
  • `extend({}, {a:{b:{c:true}}})` – dandavis May 13 '15 at 21:14
  • possible duplicate of [Automatically create object if undefined](http://stackoverflow.com/questions/17643965/automatically-create-object-if-undefined) – davidmdem May 13 '15 at 21:15

1 Answers1

0

It doesn't make sense to do it this way.

I am sure that you need it in a very special case, so I recommend you to review your purposes and use a helper function instead.

For example, setProperty(targetObj, path, value) where path is a plain list like ['key1', 'key2'], so you can check for existence there.

Also, you can combine set of keys if it makes sense. Like obj[key1 + '_' + key2]. It is also easy to write helper getter and setter for this case.

P.S. Again, you really don't want go that way. If value must be accessed by a set of keys, it is probably the one combined key. Don't make it complex.

Kirill Rogovoy
  • 583
  • 3
  • 11