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?

1
  • 2
    console.log(event.data.data.percent) ? Commented Mar 20, 2015 at 22:02

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I got confused over the data in the data.
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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.