2016-07-10 58 views
4

我有這樣的對象數組:如何合併對象數組中的重複項並對特定屬性進行求和?

var arr = [ 
    { 
     name: 'John', 
     contributions: 2 
    }, 
    { 
     name: 'Mary', 
     contributions: 4 
    }, 
    { 
     name: 'John', 
     contributions: 1 
    }, 
    { 
     name: 'Mary', 
     contributions: 1 
    } 
]; 

...我想合併重複,但總結他們的貢獻。結果將如下所示:

var arr = [ 
    { 
     name: 'John', 
     contributions: 3 
    }, 
    { 
     name: 'Mary', 
     contributions: 5 
    } 
]; 

我該如何用JavaScript實現?

+2

你嘗試過什麼到目前爲止? –

回答

3

你可以使用一個散列表並用你需要的和來生成一個新的數組。

var arr = [{ name: 'John', contributions: 2 }, { name: 'Mary', contributions: 4 }, { name: 'John', contributions: 1 }, { name: 'Mary', contributions: 1 }], 
 
    result = []; 
 

 
arr.forEach(function (a) { 
 
    if (!this[a.name]) { 
 
     this[a.name] = { name: a.name, contributions: 0 }; 
 
     result.push(this[a.name]); 
 
    } 
 
    this[a.name].contributions += a.contributions; 
 
}, Object.create(null)); 
 

 
console.log(result);

+1

您可以使用全新的ES6 Map對象:'var result = new Map(); (result.get(element.name))result.set(element.name,result.get(element.name)+ element.contributions); else result.set((element)=> {0} (element.name,element.contributions); }); console.log(result);' –

0

你也可以做這是由linq.js

這裏使用linq.js我的代碼提供,這幾乎看起來像SQL語句這樣使用LINQ框架。

var arr = [ 
 
    { 
 
     name: 'John', 
 
     contributions: 2 
 
    }, 
 
    { 
 
     name: 'Mary', 
 
     contributions: 4 
 
    }, 
 
    { 
 
     name: 'John', 
 
     contributions: 1 
 
    }, 
 
    { 
 
     name: 'Mary', 
 
     contributions: 1 
 
    } 
 
]; 
 

 

 
var aggregatedObject = Enumerable.From(arr) 
 
     .GroupBy("$.name", null, 
 
       function (key, g) { 
 
        return { 
 
         name: key, 
 
         contributions: g.Sum("$.contributions") 
 
        } 
 
     }) 
 
     .ToArray(); 
 

 
console.log(aggregatedObject);
<script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>

相關問題