Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I think I've seen how to create a JSON object without first preparing it. This is how i prepare it:

obj = {
  0:{
    type:{}
  },
  1:{},
  2:{}
};

Now I think I can insert a 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 to 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?
like image 631
Björn C Avatar asked Jun 22 '26 15:06

Björn C


1 Answers

obj = {
  0:{
    type:{}
  },
  1:{},
  2:{}
};

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

I guess you mean "assign" a value, not "insert". Anyway, no, you can't, at least not this way, because obj.0 is invalid syntax.

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

That's fine. But you need to understand you are overwriting the existing value of obj[0][type], which is an empty object ({}), with the string Type0. To put it another way, there is no requirement to provide an initialized value for a property such as type in order to assign to it. So the following would have worked equally well:

obj = {
  0:{},
  1:{},
  2:{}
};

Now let's consider your second case:

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

Think closely about what is happening. You are creating an empty obj. You can assign to any property on that object, without initializing that property. That is why the assignment to obj.test works. Then in your second assignment, you are attempting to set the test property of obj.test, which you just set to the string "test". Actually, this will work--because strings are objects that you can set properties on. But that's probably not what you want to do. You probably mean to say the previous, string value of obj.test is to be replaced by an object with its own property "test". To do that, you could either say

obj.test = { test: "test" };

Or

obj.test = {};
obj.test.test = "test";

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!