-1

I have the following object which defines the end and start times for a paragraph:

var times = {
 "p1": [24.500, 29.268],
 "p2": [29.268, 29.441],
 "p3": [29.441, 29.640]
};

I wish to call updateCurrentParagraph when the paragraph changes:

vid.addEventListener("timeupdate", function() {

    var t = this.currentTime;
    for (var key in times) {
       if (t >= times[key][0] && t < times[key][1])
       {
           updateCurrentParagraph(key);
           return;
       }
    }

    // at end of audio
    if (times[times.length-1][1] == t){
        updateCurrentParagraph(???);
        return;
    }

    updateCurrentParagraph("unknown");
    return;

});

What do I do at ??? to get "p3"?

Baz
  • 12,713
  • 38
  • 145
  • 268

2 Answers2

0

Just use Object.keys method by passing your object as argument.

var key = Object.keys(times)[0];
var values = times[key]
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

You could save the last key which has the right time for checking after the loop, if the properties are not ordered.

vid.addEventListener("timeupdate", function () {
    var t = this.currentTime,
        last;
    for (var key in times) {
        if (times[key][0] >= t && times[key][1] < t) {
            updateCurrentParagraph(key);
            return;
        }
        if (times[key][1] === t) {
            last = key;
        }
    }

    // at end of audio
    if (last) {
        updateCurrentParagraph(last);
        return;
    }

    updateCurrentParagraph("unknown");
    return;
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392