2014-09-05 91 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

相关问题