-1

I am not so into JavaScript and I have the following problem.

I have to use only plain old JS to add a brand new field to a JSON object like this:

    var dateFirestForecast = (new Date(firstForecastRetrieved.start_date)).toISOString().split('T')[0];

    var day_1 = JSON.parse(`
        {
            "day-1": {}
        }
    `);

    day_1.day-1.start_date = dateFirestForecast;

In my code I have something like the previous snippet.

The first line contains a string like 2017-11-05.

Then I have a day_1 JSON object containing a day-1 field (which is a JSON object in turn).

I am trying to add a brand new "start_date" field to this object by:

day_1.day-1.start_date = dateFirestForecast;

to obtain something like this as final result:

{
    "day-1": {
        "start_date": "2017-11-02",
    }
}

but doing in this way I am obtaining this JavaScript error in the console related to this last line:

Uncaught SyntaxError: Invalid or unexpected token

Why? What is wrong? What am I missing? How can I solve this issue?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596

1 Answers1

2

Your error is in this line:

day_1.day-1.start_date = dateFirestForecast;

That - in there is a subtraction. Since it's supposed to be part of the value's name, you'll need to use bracket access, instead:

day_1["day-1"].start_date = dateFirestForecast;
Cerbrus
  • 70,800
  • 18
  • 132
  • 147