[英]javascript/underscore: find objects by property in an array, and combine them
如果我有一个看起来像这样的对象数组:
[{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}]
现在,我正在创建一个新数组,遍历现有数组,查找具有特定名称的所有内容,进行求和,然后将其转储到新数组中。 一切似乎都太复杂了。 我正在使用下划线来处理很多繁重的工作。
谢谢!
尝试使用哈希表(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});
}
您确定结果不是正式的数组,而是传统的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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.