如何在JavaScript中按日期汇总对象属性值

时间:2014-08-08 21:55:05

标签: javascript jquery arrays object

我试图迭代一个对象数组并按日期添加类似的属性,并返回一个包含总结数据的新数组。这是一个例子:

下面的数据是针对一周中的每一天,我想获得本月电视,视频和DVD的总和。每个代码块都会有一个日期戳。

    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"

   ]

可能有更好的方法,我感谢任何建议。提前谢谢!

1 个答案:

答案 0 :(得分:0)

以下内容永远不会有效

i[key].Date.getMonth();

由于您的Date属性是一个字符串而不是Date对象,因此它会因未定义的函数错误而停止。

下面将累积数据,但不是让对象具有包含数据的名为“0”的单个属性,而是创建一个属性为{month} {year}的对象,即2014年8月,2014年7月,其中数据包含

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"
    }
}

JSFiddle Demo