Search code examples
node.jsbluebird

Promise.map over object


I've an object like;

{ '6': { stream: { twitch: [Object] } },
  '7': { stream: { twitch: [Object] } },
  '8': { stream: { twitch: [Object] } },
  '9': { stream: { twitch: [Object] } },
  '10': { stream: { twitch: [Object] } },
  '11': { stream: { twitch: [Object] } } }

I want to iterate over it like;

return Promise.map(myObj, function(minute, minuteIndex) {

so basically minute should hold the data and minuteIndex should be holding the index.

I can do it with lodash but bluebird can't somehow.

_.forEach(hour.minutes, function(minute, minuteIndex) {

I know that this code was working before but now can't get it so.

Any ideas?


Solution

  • You can map the object's keys into an array and give that to Promise.map():

    function process(stats) {
        var statsArray = Object.keys(stats).map(key => ({
            minute: key, minuteIndex: stats[key]
        }));
        return Promise.map(statsArray, item => {
            // work with item.minute & item.minuteIndex
        });
    }
    

    Usage:

    var twitchStats = {
      '6': { stream: { twitch: [Object] } },
      '7': { stream: { twitch: [Object] } },
      '8': { stream: { twitch: [Object] } },
      '9': { stream: { twitch: [Object] } },
      '10': { stream: { twitch: [Object] } },
      '11': { stream: { twitch: [Object] } }
    };
    
    process(twitchStats).then(result => {
        // ...
    });