javascript - Assign nested object to object JS -
this might have been asked before, didn't see question:
is there way declare object in javascript such can directly assign values in multiple levels of nesting (without declaring each level along way)?
example:
var obj = {}; obj["key1"]["key2"]["key3"] = "value"; obj["key1"]["key4"]["key5"] = "value2;
the above doesn't work me, since i'm creating object dynamically, creating each level along way each key costly i'd have check existence first..
ie:
if (!obj["key1"]) obj["key1"] = {}; elseif (!obj["key1"]["key2"]) !obj["key1"]["key2"] = {}; ... etc
i hope makes sense.
it doesn't make sense way.
i sure need in special case, recommend review purposes , use helper function instead.
for example, setproperty(targetobj, path, value)
path
plain list ['key1', 'key2']
, can check existence there.
also, can combine set of keys if makes sense. obj[key1 + '_' + key2]
. easy write helper getter , setter case.
p.s. again, don't want go way. if value must accessed set of keys, 1 combined key. don't make complex.
Comments
Post a Comment