3

I have a object with printout from a console.log() command:

console.log("event in validation ", this.event_info);

Here is the printout:

event in validation  {"start_datetime":"Sun Jul 14 2019 18:20:00 GMT-0700 (PDT)","finish_datetime":"Mon Jul 15 2019 18:20:00 GMT-0700 (PDT)"}

There are 2 fields in this.event_info: start_datetime and finish_datetime. I need to refer the value of finish_datetime and did the following:

this.event_info["finish_datetime"];

and

let sd = "finish_datetime";
this.event_info[sd];

But there are nothing retrieved (undefined or nothing). Then I tried to print out the keys of the object:

 Object.keys(this.event_info);

And printout is:

 [ '0',
  '1',
  '2',
  '3',
  .
  .
  .
  99

Then I tried these:

 this.event_info["1"];

and:

this.event_info[1];

It is nothing printed out again. What is the right way here to refer the value of finish_datetime?

user938363
  • 9,990
  • 38
  • 137
  • 303
  • Are you sure you don't overwrite the variable? You should show us the entire code to see where the problem comes from – Mihai Matei Jul 15 '19 at 06:24
  • 6
    `this.event_info` is a JSON string. You want `JSON.parse(this.event_info).finish_datetime` – Phil Jul 15 '19 at 06:25
  • @Phil I bet your comment is right, don't you want to write an answer with that info? If this is not a duplicate it is a good question. – Raul Sauco Jul 15 '19 at 06:28
  • 1
    @RaulSauco I'd say it classifies as a _typo_ / no longer a problem. A modicum of debugging (like with a debugger) would reveal the data type of OP's variable. The only real take-away from this is that `console.log()` is **not** a debugging tool. – Phil Jul 15 '19 at 06:31
  • 1
    **Object.keys(obj)** returns the keys of your object. **Object.values(obj)** returns the values and **Object.entries(obj)** returns an array of arrays ([key, value]) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries. So it's not surprising that for **Object.keys(obj)** you get an array of numbers. – muka.gergely Jul 15 '19 at 06:32
  • @Phil fair enough – Raul Sauco Jul 15 '19 at 06:32
  • @RaulSauco changed my mind and added a community-wiki answer below. Feel free to help improve it, especially the list of debugging tools – Phil Jul 15 '19 at 06:46

1 Answers1

2

Long Answer

console.log() is a terrible debugging tool. It does not show data types and what it shows is not always a correct representation of the state of your application at the time you call it.

You should instead use your browser's actual debugger or one connected via your editor / IDE.

Short Answer

Your variable is a JSON string, not an object. You want

JSON.parse(this.event_info).finish_datetime
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Save my day and thank you! I was confused by https://www.w3schools.com/js/js_json_objects.asp and treated it as JSON object instead of JSON string. – user938363 Jul 15 '19 at 13:43