如何在JavaScript中按日期汇总对象属性值
我试图迭代一个对象数组,按日期添加类似的属性,并返回一个包含汇总数据的新数组。以下是一个例子: 下面的数据是一周中的每一天,我想得到这个月的电视、视频和DVD的总和。每段代码都有日期戳如何在JavaScript中按日期汇总对象属性值,javascript,jquery,arrays,object,Javascript,Jquery,Arrays,Object,我试图迭代一个对象数组,按日期添加类似的属性,并返回一个包含汇总数据的新数组。以下是一个例子: 下面的数据是一周中的每一天,我想得到这个月的电视、视频和DVD的总和。每段代码都有日期戳 var i = [ { "0":{ "TV":"200", "Video":"50", "DVD":"150", "Date":"Fri Jul 18 2014 19:00:00 GMT-0500" }
var i = [
{
"0":{
"TV":"200",
"Video":"50",
"DVD":"150",
"Date":"Fri Jul 18 2014 19:00:00 GMT-0500"
}
},
{
"1":{
"TV":"150",
"Video":"60",
"DVD":"150",
"Date":"Fri Jul 25 2014 19:00:00 GMT-0500"
}
},
{
"2":{
"TV":"350",
"Video":"20",
"DVD":"150",
"Date":"Wed Aug 01 2014 19:00:00 GMT-0500"
}
},
{
"3":{
"TV":"200",
"Video":"50",
"DVD":"100",
"Date":"Thurs Aug 08 2014 19:00:00 GMT-0500"
}
} continues.....
]
下面是我正在研究的方法
var newObj = [];
for(var key in i){
var thisMonth = i[key].Date.getMonth();
if(thisMonth === 6){
//Add each properties together and push to the new array
console.log(thisMonth); //this results in two 6 (july).
}else if(thisMonth === 7){
//Add each properties together and push to the new array
console.log(thisMonth); //this results in two 7 (August).
}
}
return newObj;
我希望这个方法返回一个包含所有汇总数据的新数组
[
{
"0":{
"TV":"350",
"Video":"110",
"DVD":"300",
"Date":"Jul 2014"
},{
"0":{
"TV":"550",
"Video":"70",
"DVD":"250",
"Date":"Aug 2014"
]
也许有更好的方法,我很感激你的建议。提前谢谢 下面的方法永远不会奏效
i[key].Date.getMonth();
由于日期属性是字符串而不是日期对象,因此它会由于未定义的函数错误而停止
下面将累积数据,但这将创建一个属性为{month}{year}的对象,即2014年8月、2014年7月,其中包含数据,而不是一个名为0的对象包含数据
var data = {};
//Loop over the array, use a regular for loop or
//forEach polyfill if supporting older browsers
i.forEach(function(item,index){
//Since the object we want is a property
//of the item object use the index as the key
var obj = item[index];
var d = new Date(obj.Date);
//alternative way to get abbr. month then creating
//an array of months and using the getMonth as an index to that array
var m = d.toDateString().split(" ")[1];
var y = d.getFullYear();
//Check to see if there already is a month/year
//property creating one if not.
var temp = data[m+" "+y] || {"TV":0,"Video":0,"DVD":0,"Date":""};
temp.TV += +obj.TV;
temp.Video += +obj.Video;
temp.DVD += +obj.DVD;
temp.Date = m+" "+y;
data[m+" "+y] = temp;
});
console.log(data);
将记录数据对象,并具有以下格式:
{
"Jul 2014": {
"TV": 350,
"Video": 110,
"DVD": 300,
"Date": "Jul 2014"
},
"Aug 2014": {
"TV": 550,
"Video": 70,
"DVD": 250,
"Date": "Aug 2014"
}
}
是否有一个特定的问题让您很难处理?这里有一些东西让您开始:输入和输出数据真的是双重包装对象的数组,还是这只是手工序列化的一个怪癖?看到简单的物体阵列会更传统。谢谢elzi!Nit-我遇到的问题是按日期添加所有项目,然后返回添加项目的数组。Roamer-我正在使用剑道ui来可视化这些数据,我需要将数组传递给剑道图表。请看一个输出数组的解决方案,类似于您想要的,但没有双重包装。要使用它,您需要预处理源数据结构并对我的输出数组进行后处理。作为一个对象,输出将是无序的,这可能是一个问题。在Javascript中,只有数组有顺序。哇,帕特里克!谢谢你帮我把这些整理好。我也可以使用for-in-loop。当我在forEach循环中尝试Date属性时,它似乎不适合我