2014-09-05 59 views
2

如果我有對象的數組,看起來像這樣:的JavaScript /下劃線:查找財產對象的數組,並結合他們

[{id:1,product:'widget',quantity:10}, {id:2,product:'foobar',quantity:5}, {id:3,product:'widget',quantity:5}] 

是否有JavaScript的一種優雅的方式來找到具有相同的對象名稱,並將這些數量合併到第一個對象中,然後刪除剩餘的數量?

結果數組是這樣的:

[{id:1,product:'widget',quantity:15}, {id:2,product:'foobar',quantity:5}] 

現在我正在創建一個新的數組,迭代現有陣列上,具有特定名稱找到任何東西,做的總和,然後爲之傾倒進入新陣列。這一切似乎過於複雜。我使用下劃線來處理很多繁重的工作。

謝謝!

回答

0

嘗試使用哈希表(對象在Javascript):

var data = new Array(
    {id:1,product:'widget',quantity:10}, 
    {id:2,product:'foobar',quantity:5}, 
    {id:3,product:'widget',quantity:5} 
); 
var temp = new Object(); 
var newdata = new Array(); 

// Stuff your quantities into the hash table 
for (var i=0; i<data.length; i++) { 
    // If the product doesn't exist yet, create it and set the quantity to 0 
    if (!temp.hasOwnProperty(data[i].product)) { 
     temp[data[i].product] = 0; 
    } 
    // Increment the product quantity 
    temp[data[i].product] += data[i].quantity; 
} 

// Split out the hash table into an array 
for (product in temp) { 
    newdata.push({"id":newdata.length+1, "product":product, "quantity":temp.product}); 
} 
+0

爲什麼要使用完整的'Array'和'Object'構造函數? – Rudie 2014-09-05 18:39:28

+0

這基本上是凱文描述的解決方案,已經到位了。他希望使用underscore.js更優雅。 – 2014-09-05 19:00:13

0

你沒事帶不是一個正式的陣列,而是一個傳統的對象,結果呢?因爲真的,數組只是一種特殊類型的Object。這樣,您就可以訪問它,就好像它是一個關聯數組,您可以訪問基於產品,這似乎是你關心什麼名稱:

var results = {}; 
for(var i = 0; i < yourarr.length; ++i) { 
    if(!results.hasOwnProperty(yourarr[i].product)) { 
    results[yourarr[i].product] = {}; 
    results[yourarr[i].product].id = yourarr[i].id; 
    results[yourarr[i].product].quantity = yourarr[i].quantity; 
    } 

    results[yourarr[i].product].quantity += yourarr[i].quantity; 
} 

//Can now access by doing say, console.log(results.widget); 
//To loop through, you can do: 
for(var key in results) { 
    if(results.hadOwnProperty(key) { //Needed to ensure you don't access prototype elements 
    console.log(results.key); 
    } 
} 
3

你可以groupBy產品,然後map的結果組得到所需的結構。 Reduce用於總和數量:

​​
+0

+1,只有實際使用underscore.js的答案 – 2014-09-05 18:59:12

相關問題