1

I need to be able to get the value of an object key. When I console.log(event); a returned object, I am getting:

MessageEvent {
    ports: Array[0], 
    data: "{
        "event":"playProgress",
        "data":{
            "seconds":0.419,
            "percent":0.002,
            "duration":177.813
        }
    }"
}

I can't seem to get to value of the data.percent with console.log(event.data.percent). What am I doing wrong?

superUntitled
  • 22,351
  • 30
  • 83
  • 110

3 Answers3

4

It looks like event.data is actually a string, and not a nested object. With a "reasonably modern" browser, you can:

var data = JSON.parse(event.data);
console.log(data.percent);

More discussion on JSON.parse can be seen at this previous stackoverflow answer.

Community
  • 1
  • 1
lsowen
  • 3,728
  • 1
  • 21
  • 23
0

Remove the quotes around your first data object

MessageEvent {
    ports: Array[0], 
    data: {
        "event":"playProgress",
        "data":{
            "seconds":0.419,
            "percent":0.002,
            "duration":177.813
        }
    }
}

By leaving them in your creating a string rather then an obj

MarcJames
  • 189
  • 9
0

You need to go down another level in your MessageEvent object to access the subobject data of the first data object. In order to console.log you don't even need to stringify and then parse the object, like in this case.

Try below:

var MessageEvent = {
    ports: Array[0], 
    data: {
        "event":"playProgress",
        "data":{
            "seconds":0.419,
            "percent":2.002,
            "duration":177.813
        }
    }
};

console.log(MessageEvent.data.data.percent);

JSFiddle: http://jsfiddle.net/a_incarnati/em3afkov/

Alessandro Incarnati
  • 7,018
  • 3
  • 38
  • 54