0

I am trying to create a JSON Array:

let someJSON = {};
someJSON["number1"] = "someString";

works. But when I want to set a "Child" to number1 it fails:

someJSON["number1"]["date"] = "19.01.2017";

I tried some things but its not working :( I need to create the JSON like this because I needs variables as parents

dunklesToast
  • 344
  • 3
  • 16
  • 3
    There is no JSON in the question. JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Jan 18 '17 at 18:20
  • 1
    You're also not creating an array (which would use `[]`). You're creating an object (`{}`). – Heretic Monkey Jan 18 '17 at 18:22

2 Answers2

1

I am trying to create a JSON Array:

let someJSON = {};
someJSON["number1"] = "someString";

That's not a JSON array, that's a JavaScript object.

But when I want to set a "Child" to number1 it fails:

someJSON["number1"]["date"] = "19.01.2017";

That's because you're setting a property on a string primative. That will temporarily promote the string primative to an object, set the property, and then throw away the object, effectively doing nothing.

To make someJSON.number an object, create an object just like you did for someJSON and add properties to it. Or you can do it all at once:

let obj = {
    number1: {
        date: "19.01.2017"
    }
};

If you want "someString" in there somewhere, just put it on another property:

let obj = {
    number1: {
        str:  "someString",
        date: "19.01.2017"
    }
};
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Might be worth noting that if they want to have a string value (`"someString"`), they can add another property to hold that. E.g., `obj = { number1: { – Heretic Monkey Jan 18 '17 at 18:25
0

You have to create the "number1" object first. Note that you won't be able to set a string value for "number1" as it is now an object.

let someJSON = {};
someJSON["number1"] = {};
someJSON["number1"]["date"] = "19.01.2017";
Eric
  • 9,870
  • 14
  • 66
  • 102