Mjukis Mjukis - 1 month ago 5
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 = {
0:{
type:{}
},
1:{},
2:{}
};


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"!

EDIT


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

Is it necessary to create nested objects before using it?

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

Example:

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;

console.log(object);

Comments