Skip to content Skip to sidebar Skip to footer

Json Sibling Data

(forgive me if I use slightly incorrect language - feel free to constructively correct as needed) There are a couple posts about getting data from JSON data of siblings in the retu

Solution 1:

You can use the following function:

functionfindSum(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.

vardata = {};
var array = ResultSet.Result;

var i = 0;
var currentDesc, currentSize;
var sizeDiv;
var sumItem;

//Sum the sizes for each descriptionfor(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 pagefor(sumItem indata) {
    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 Storagefor(var i = 0; i < result.length; i++) {
  sum[result[i].desc] = 0; 
}

// Sum the matching file sizefor(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);
    }   
}

DEMO:http://jsfiddle.net/HtrLu/1/

Post a Comment for "Json Sibling Data"