superUntitled
superUntitled

Reputation: 22567

Getting the value of a js object key

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?

Upvotes: 1

Views: 921

Answers (3)

Alessandro Incarnati
Alessandro Incarnati

Reputation: 7246

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/

Upvotes: 0

MarcJames
MarcJames

Reputation: 189

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

Upvotes: 0

lsowen
lsowen

Reputation: 3838

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.

Upvotes: 4

Related Questions