将promisevariables分解成命名variables

我有这样的事情

Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) 

但后来我只是得到一个数组,其中每个元素是在特定类别中的Collection中find的项目的数组。

我想要的是返回一个对象,其中的键是类别。

所以如果我的类别是footballvolleyballmotorsport ,我想要

 { 'football': [...], 'volleyball': [...], 'motorsport': [...] } 

代替

 [ [...], [...], [...] ] 

就像我现在一样。

如果类别的数量是静态的,我想我可以做这样的事情

 Promise.all( categories.map(category => Collection.find({ category })) ).then(([football, volleyball, motorsport]) => { return { football, volleyball, motorsport } }) 

由于items数组的顺序与categories数组的顺序相似,因此可以使用Array#reduce将它们组合到使用该项目的对象以及相同索引的类别标签中:

 Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items.reduce((o, item, i) => { o[categories[i]] = item; return o; }, {}); }) 

而且由于您使用的是ES6,您可能需要创build一个Map :

 Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items.reduce((map, item, i) => map.set(categories[i], item), new Map()); })