简体   繁体   中英

how to calculate values of an (javascript) object with date keys

I have the following simplified (javascript) object, of which properties are dates (in string fomat):

Given a random startdate and enddate within the range of dates in the object, how to code (efficiently) the calculation - say accumulate- of the values within this range? As an example, for the following code the calculation result should be 12 (3+4+5) for the given startdate and enddate.

var startdate = '2014-01-03';
var enddate = '2014-01-05'
var obj = {};
obj['2014-01-02'] = '2';
obj['2014-01-03'] = '3';
obj['2014-01-04'] = '4';
obj['2014-01-05'] = '5';
obj['2014-01-06'] = '6';

You can just loop through the properties of the object, doing a comparison, and adding.

var startdate = '2014-01-04';
var enddate = '2014-01-05';
var arr = {};
arr['2014-01-02'] = '2';
arr['2014-01-03'] = '3';
arr['2014-01-04'] = '4';
arr['2014-01-05'] = '5';
arr['2014-01-06'] = '6';

var total = 0;
for(var p in arr) {
  if(arr.hasOwnProperty(p)) {
      if(new Date(p) >= new Date(startdate) && new Date(p) <= new Date(enddate)) {
        total += parseInt(arr[p], 10);
      }
   }
}

console.log(total);

Sample http://jsbin.com/imUdewaJ/1/edit

I'm sure there is a better way to do this, but I don't know how due to having to parse the date object out for comparison.

--Edit added in the hasOwnProperty check from comments below

It's possible that some browsers won't support date1 > date2 , so it might be better to also use getTime() .

function getDate(date) {
  return new Date(date).getTime();
}

function getTotal(start, end) {
  var total = 0;
  for (var k in obj) {
    var current = getDate(k);
    if (current >= start && current <= end) {
      total += parseInt(obj[k], 10);
    }
  }
  return total;
}

var start = getDate(startdate);
var end = getDate(enddate);

console.log(getTotal(start, end)); // 12

When doing stuff with dates, you might want to use thirdparty tools to handle browser compatibility. Momentjs is a good one for dates.

solution with momentjs :

var startdate = moment('2014-01-03');
var enddate = moment('2014-01-05');

var obj = {};
obj['2014-01-02'] = '2';
obj['2014-01-03'] = '3';
obj['2014-01-04'] = '4';
obj['2014-01-05'] = '5';
obj['2014-01-06'] = '6';

var strDate;
var total = 0;
for (strDate in obj) {
    if (obj.hasOwnProperty(strDate)) {
        var date = moment(strDate)
        if (date.diff(startdate, 'days')>=0 && date.diff(enddate, 'days')<=0) {
            total += parseInt(obj[strDate], 10);
        }
    }
}

console.log(total);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM