Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@voxpelli
Last active April 19, 2022 12:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save voxpelli/2c9b58e5fef9ed46a2cbfef21416d0e2 to your computer and use it in GitHub Desktop.
Save voxpelli/2c9b58e5fef9ed46a2cbfef21416d0e2 to your computer and use it in GitHub Desktop.
A recursive Promise.all() that works on objects
const zipObject = function (keys, values) {
const result = {};
keys.forEach((key, i) => {
result[key] = values[i];
});
return result;
};
const recursiveObjectPromiseAll = function (obj) {
const keys = Object.keys(obj);
return Promise.all(keys.map(key => {
const value = obj[key];
// Promise.resolve(value) !== value should work, but !value.then always works
if (typeof value === 'object' && !value.then) {
return recursiveObjectPromiseAll(value);
}
return value;
}))
.then(result => zipObject(keys, result));
};
@KittyGiraudel
Copy link

KittyGiraudel commented Nov 24, 2016

I would probably author zipObject like this:

const zipObject = (keys = [], values = []) => {
  return keys.reduce((accumulator, key, index) => {
    accumulator[key] = values[index]
    return accumulator
  }, {})
}

:)

@voxpelli
Copy link
Author

@hugogiraudel Good point!

@kalasjocke
Copy link

Great gist. Thanks! 👍

@rodnierbc
Copy link

Thanks, this is great - Promise.All should have always been recursive and worked to return the data in the same layout as it was provided.

@chumager
Copy link

shorter ;)

const zipObject = (keys = [], values = []) => keys.reduce((accumulator, key, index) => Object.assign(accumulator,{[key]: values[index]}),{});

I would probably author zipObject like this:

const zipObject = (keys = [], values = []) => {
  return keys.reduce((accumulator, key, index) => {
    accumulator[key] = values[index]
    return accumulator
  }, {})
}

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment