Skip to content

Instantly share code, notes, and snippets.

@Swivelgames
Created September 25, 2017 16:55
Show Gist options
  • Select an option

  • Save Swivelgames/630ca47ec20943f8a9a9e7761ecff972 to your computer and use it in GitHub Desktop.

Select an option

Save Swivelgames/630ca47ec20943f8a9a9e7761ecff972 to your computer and use it in GitHub Desktop.
Obj Flatten, then Reduce Promises
const obj = { "foo": { "bar": "0", "pew": "hell world" }, "quux": { "baz": "1", "world": "wonderful" }};
const flatObj = Object.keys(obj).reduce((retObj, key) => Object.assign({},
retObj,
Object.keys(obj[key]).reduce((deepRetObj, deepKey) => Object.assign({},
deepRetObj,
{ [`${key}.${deepKey}`]: obj[key][deepKey] }
), {})
), {});
console.log(JSON.stringify(flatObj));
Object.keys(flatObj).reduce((prevProm, key) => (
prevProm.then((prevVal) =>
new Promise(
resolve => { setTimeout(() => { console.log(key); resolve(key); }, 1000); }
)
)
), Promise.resolve()).then(
(output) => { console.info(JSON.stringify(output)); },
(errors) => { console.error(JSON.stringify(errors)); }
);
@Swivelgames
Copy link
Copy Markdown
Author

Sample output:

{"foo.bar":"0","foo.pew":"hell world","quux.baz":"1","quux.world":"wonderful"}
foo.bar
foo.pew
quux.baz
quux.world
"quux.world"
[Finished in 4.143s]

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