2

I have a javascript object in a dictionary that looks like this:

{ date: "2010/01", San_Francisco201001: 1, San_Francisco201002: 2, San_Francisco201003: 3, }, { date: "2010/02", San_Francisco201001: 0, San_Francisco201002: 1, San_Francisco201003: 2, }

And would like to find

{ date: "2010/01", sum: 6, ), { date: "2010/02", sum: 3, )

It gets a bit tricky, because the property names are arbitrary. Any clue how to go about doing this?

Thanks.

2
  • So everything but the date should be added? Commented Oct 28, 2010 at 23:26
  • I removed the json tag, because this has nothing to do with JSON. Commented Oct 28, 2010 at 23:34

4 Answers 4

3

That is not one object, that is two objects. I assume that you have them in an array. Then you can loop through the array, and loop through the properties in each object:

var result = [];
for (var i = 0; i < theArray.length; i++) {
  var sum = 0;
  for (var key in theArray[i]) {
    if (key != 'date') {
      sum += theArray[i][key];
    }
  }
  result.push({ date: theArray[i].date, sum: sum });
}
Sign up to request clarification or add additional context in comments.

Comments

0

To find the sum of a particular date value, create a function with a body like this:

function getDate(date, arr) {
    for(var i = arr.length; i--;) {
        if(arr[i].date === date) {
            var obj = { sum: 0; };
            for(var prop in arr[i]) {
                if(prop !== "date") {
                    obj.sum += arr[i][prop];
                }
            }
            obj.date = obj.date;
            return obj;
        }
    }
}

Comments

0

This should work:

var data = [{ date: "2010/01", San_Francisco201001: 1, San_Francisco201002: 2, San_Francisco201003: 3, }, { date: "2010/02", San_Francisco201001: 0, San_Francisco201002: 1, San_Francisco201003: 2, }];

var result = [];

for(var i = 0; i < data.length; i++) {
   var dateData = data[i];
   var sum = 0;

   for(var element in dateData) if(dateData.hasOwnProperty(element)) {
      var elementData = dateData[element];

      if(element != "date") {
         sum += elementData;
      }
   }

   result.push({date: dateData["date"], sum: sum});
}

Comments

0
var data = [{ date: "2010/01", San_Francisco201001: 1, San_Francisco201002: 2, San_Francisco201003: 3 }, { date: "2010/02", San_Francisco201001: 0, San_Francisco201002: 1, San_Francisco201003: 2 }];

var out = {};
for(var row in data){

    var stats = data[row];
    var cnt = 0;
    for(var itm in stats){
        if(itm==="date")continue;
        cnt += stats[itm];
    }
    out[stats["date"]] = cnt;
}

alert( out["2010/01"] );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.