2017-02-23 113 views
0

我得到了一組對象(任務)。每個任務都具有名爲「類別」和「持續時間」的屬性。按屬性的唯一值分組

var tasks = [ 
{ 
_id : "123", 
category : "someCategory", 
duration: "3432" 
}, 
{ 
_id : "113", 
category : "someCategory", 
duration: "23" 
}, 
{ 
_id : "124", 
category : "someCategory 2", 
duration: "1343" 
}, 

{ 
_id : "2124", 
category : "someCategory 2", 
duration: "1343" 
}, 

{ 
_id : "7124", 
category : "someCategory 5", 
duration: "53" 
}, 

{ 
_id : "34", 
category : "someCategory", 
duration: "753" 
} 
] 

我想按類別(唯一)和每個類別的總持續時間分組任務。

結果應該是這樣的:

var categories = ["someCategory", "someCategory 2" ... ] 
    var duration = [ <summary duration of "someCategory">, <summary duration of "someCategory 2">, ... ] 

我有GROUPBY功能,給了我所有類別。我可以使用Array.prototype.filter找到唯一的類別,但仍然需要總結「持續時間」。

var categoryMap = groupBy(tasks, 'category'); 
     var uniqueCategories = categoryMap.get('category').filter((x, i, a) => a.indexOf(x) == i); 

    function groupBy(list, property) { 
      var map = new Map(); 
      list.forEach(function(item) { 
       const key = property; 
       if(!map.has(key)) { 
        map.set(key, [item[key]]) 
       } else { 
        map.get(key).push(item[key]) 
       } 
      }) 
      return map; 
      } 

然後,我創建的數組{鍵:值}和總和鍵即

[ 
    { 
    someCategory : 3432 
    }, 
    { 
    someCategory : 23 
    } 
. 
. 
. 
] 

最後我實現我的目標,但代碼看起來混亂和不可讀在所有... 是有更好的方法來做到這一點在Javascript中?

回答

3

您可以用category: duration返回一個對象。

var tasks = [{"_id":"123","category":"someCategory","duration":"3432"},{"_id":"113","category":"someCategory","duration":"23"},{"_id":"124","category":"someCategory 2","duration":"1343"},{"_id":"2124","category":"someCategory 2","duration":"1343"},{"_id":"7124","category":"someCategory 5","duration":"53"},{"_id":"34","category":"someCategory","duration":"753"}] 
 

 
var result = tasks.reduce(function(r, e) { 
 
    r[e.category] = (r[e.category] || 0) + +e.duration 
 
    return r; 
 
}, {}) 
 

 
console.log(result)

2

var tasks = [{"_id":"123","category":"someCategory","duration":"3432"},{"_id":"113","category":"someCategory","duration":"23"},{"_id":"124","category":"someCategory 2","duration":"1343"},{"_id":"2124","category":"someCategory 2","duration":"1343"},{"_id":"7124","category":"someCategory 5","duration":"53"},{"_id":"34","category":"someCategory","duration":"753"}] 
 

 
var arr = []; 
 
tasks.forEach(v => arr.push(v.category)); 
 
var newArr = [...new Set(arr)]; 
 
var arr2 = []; 
 

 
newArr.forEach(function(v) { 
 
    var obj = {}; 
 
    obj.category = v; 
 
    obj.duration = 0; 
 
    arr2.push(obj); 
 
}); 
 

 
arr2.forEach(v => tasks.forEach(c => c.category == v.category ? v.duration += parseInt(c.duration) : v)); 
 
console.log(arr2);