javascript - Split promise variable into named variables -
i have this
promise.all( categories.map(category => collection.find({ category })) ).then(items => { return items }) but array same length categories each element array of items found in collection within specific category.
what want return object keys categories.
so if categories football, volleyball, , motorsport, want
{ 'football': [...], 'volleyball': [...], 'motorsport': [...] } instead of
[ [...], [...], [...] ] as have now.
if number of categories static, guess this
promise.all( categories.map(category => collection.find({ category })) ).then(([football, volleyball, motorsport]) => { return { football, volleyball, motorsport } })
since items array has similar order of categories array, can use array#reduce combine them object using item, , category label of same index:
promise.all( categories.map(category => collection.find({ category })) ).then(items => { return items.reduce((o, item, i) => { o[categories[i]] = item; return o; }, {}); }) and since using es6, might want create map instead:
promise.all( categories.map(category => collection.find({ category })) ).then(items => { return items.reduce((map, item, i) => map.set(categories[i], item), new map()); })
Comments
Post a Comment