将promise变量拆分为命名变量

时间:2017-09-11 05:18:33

标签: javascript arrays node.js mongoose promise

我有类似的东西

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

然后我得到一个与categories长度相同的数组,其中每个元素都是特定类别中Collection中找到的项目的数组。

我想要的是返回键是类别的对象。

因此,如果我的类别为footballvolleyballmotorsport,我想要

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

而不是

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

就像我现在一样。

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

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

1 个答案:

答案 0 :(得分:1)

由于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,因此您可能需要创建一个Map

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