Sum javascript object property在对象数组中具有相同对象propertyB的值 [英] Sum javascript object propertyA values with same object propertyB in array of objects
本文介绍了Sum javascript object property在对象数组中具有相同对象propertyB的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取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.
这篇关于Sum javascript object property在对象数组中具有相同对象propertyB的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文