Json Sibling Data
Solution 1:
You can use the following function:
function findSum(description, array) {
    var i = 0;
    var sum = 0;
    for(i = 0; i < array.length; i++) {
        if(array[i]["desc"] == description && array[i].hasOwnProperty("file_size")) {
            sum += parseInt(array[i]["file_size"], 10);
        }
    }
    alert(sum);
}
And call it like this:
findSum("description1", ResultSet.Result);
To display an alert with the summation of all "description1" file sizes.
A working JSFiddle is here: http://jsfiddle.net/Q9n2U/.
In response to your updates and comments, here is some new code that creates some divs with the summations for all descriptions. I took out the hasOwnProperty code because you changed your data set, but note that if you have objects in the data array without the file_size property, you must use hasOwnProperty to check for it. You should be able to adjust this for your jQuery .each fairly easily.
var data = {};
var array = ResultSet.Result;
var i = 0;
var currentDesc, currentSize;
var sizeDiv;
var sumItem;
//Sum the sizes for each description
for(i = 0; i < array.length; i++) {
    currentDesc = array[i]["desc"];
    currentSize = parseInt(array[i]["file_size"], 10);
    data[currentDesc] =
        typeof data[currentDesc] === "undefined"
        ? currentSize
        : data[currentDesc] + currentSize;
}
//Print the summations to divs on the page
for(sumItem in data) {
    if(data.hasOwnProperty(sumItem)) {
        sizeDiv = document.createElement("div");
        sizeDiv.innerHTML = sumItem + ": " + data[sumItem].toString();
        document.body.appendChild(sizeDiv);
    }
}
A working JSFiddle is here: http://jsfiddle.net/DxCLu/.
Solution 2:
That's an array embedded in an object, so
data.ResultSet.Result[2].file_size
would give you 778174
Solution 3:
var sum = {}, result = ResultSet.Result
// Initialize Sum Storage
for(var i = 0; i < result.length; i++) {
  sum[result[i].desc] = 0; 
}
// Sum the matching file size
for(var i = 0; i < result.length; i++) {
  sum[result[i].desc] += parseInt(result[i]["file_size"]
}
After executing above code, you will have a JSON named sum like this
sum = {
  "description1": 20477629,
  "description2": 1246092
};
Solution 4:
An iterate like below should do the job,
var result =  data.ResultSet.Result;
var stat = {};
for (var i = 0; i < result.length; i++) {    
    if (stat.hasOwnProperty(result[i].cat_desc)) {       
        if (result[i].hasOwnProperty('file_size')) {
        stat[result[i].cat_desc] += parseInt(result[i].file_size, 10);   
        }
    } else {
        stat[result[i].cat_desc] = parseInt(result[i].file_size, 10);
    }   
}
Post a Comment for "Json Sibling Data"