Mjukis Mjukis - 9 months ago 33
JSON Question

Is it necesay to create nested jSON objects before using it?

I think i've seen how to create a JSON object without first prepare it?!

This is how i prepare it:

obj = {

Now i think i can insert value like:
obj.0.type = "type0";

But i'd like to create it while using it:
obj['0']['type'] = "Type0";

Is it possible, or do i need to prepare it?

I'd like ti create it "on the fly"!


I'd like to create JS object "On the fly".

var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?

Answer Source

Is it necessary to create nested objects before using it?

Yes it is, at least the parent object must exist.


var object = {};

// need to assign object[0]['prop'] = 42;

create the first property with default

object[0] = object[0] || {};

then assign value

object[0]['prop'] = 42;

var object = {};

object[0] = object[0] || {};
object[0]['prop'] = 42;