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?

7
  • Are you sure you don't overwrite the variable? You should show us the entire code to see where the problem comes from Commented Jul 15, 2019 at 6:24
  • 6
    this.event_info is a JSON string. You want JSON.parse(this.event_info).finish_datetime Commented Jul 15, 2019 at 6: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. Commented Jul 15, 2019 at 6: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. Commented Jul 15, 2019 at 6: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]) - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. So it's not surprising that for Object.keys(obj) you get an array of numbers. Commented Jul 15, 2019 at 6:32

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Save my day and thank you! I was confused by w3schools.com/js/js_json_objects.asp and treated it as JSON object instead of JSON string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.