将对象数组中具有相同对象 propertyB 的 javascript 对象 propertyA 值求和 [英] Sum javascript object propertyA values with same object propertyB in array of objects
本文介绍了将对象数组中具有相同对象 propertyB 的 javascript 对象 propertyA 值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取一个 javascript 对象数组,例如:
How would one take a javascript array of objects such as:
my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23},
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:54}]
并通过对值求和来合并重复的键.为了得到这样的东西:
and merge duplicate keys by summing the values. In order to get something like this:
my reducedObjArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:96},
{key:Mon Sep 24 2013 00:00:00 GMT-0400, val:78},
{key:Mon Sep 25 2013 00:00:00 GMT-0400, val:23}]
我尝试迭代并添加到一个新数组,但这没有用:
I have tried iterating and adding to a new array, but this didn't work:
var reducedObjArr = [];
var item = null, key = null;
for(var i=0; i<objArr.length; i++) {
item=objArr[i];
key = Object.keys(item)[0];
item=item[key];
if(!result[key]){
result[key] = item;
}else{
result[key] += item;}
}a
推荐答案
您应该使用 .key
属性将每个未找到的对象分配给结果.
You should be assigning each object not found to the result with its .key
property.
如果找到了,则需要添加它的.val
.
If it is found, then you need to add its .val
.
var temp = {};
var obj = null;
for(var i=0; i < objArr.length; i++) {
obj=objArr[i];
if(!temp[obj.key]) {
temp[obj.key] = obj;
} else {
temp[obj.key].val += obj.val;
}
}
var result = [];
for (var prop in temp)
result.push(temp[prop]);
<小时>
此外,部分问题是您重用了 item
变量来引用 .key
的值,因此您丢失了对该对象的引用.
Also, part of the problem was that you were reusing the item
variable to reference the value of .key
, so you lost reference to the object.
这篇关于将对象数组中具有相同对象 propertyB 的 javascript 对象 propertyA 值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文