2017-09-11 25 views
2

我有這樣的事情拆分承諾可變進命名變量

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 
    } 
}) 
+0

是否在包含該類別的'name'的類別中有任何字段? –

回答

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()); 
}) 
+0

謝謝!但是用'reduce'重新遍歷整個數組並不是很慢嗎?是不是有可能將它分割爲參數'.then(.... => ...)'?另外,我可以將它作爲JSON而不是Map返回嗎? – Jamgreen

+0

似乎我只能用你的第一個解決方案來獲得一個對象而不是地圖:-D – Jamgreen

+0

你需要知道每個類別的名稱,並且由於它們不是靜態的,所以你需要再次循環。對象與地圖是我寫**的原因,你可能想** :) –