Vinit Desai
Vinit Desai

Reputation: 520

Categorising json data and storing it in separate arrays

I want to categorize json data based on e value using jquery/javascript. For eg. if e:0, store it in separate array1 and get the count, if e:1 store it in array2 and get count and so on. Here is my json file item.json

{
"mydata":[
     {
        "xvalue": "4 Oct 2015",
        "yvalue": 53,
            "e": 3
    }, {
        "xvalue": "5 Oct 2015",
        "yvalue": 67,
            "e": 3
    }, {
        "xvalue": "6 Oct 2015",
        "time":"1.00 PM",
            "yvalue": 99,
            "e": 2
    }, {
        "xvalue": "7 Oct 2015",
        "yvalue": 80,
            "e": 1
    }, {
        "xvalue": "8 Oct 2015",
        "yvalue": 160,
             "e": 0
    }]
}

How do I call a json file and the push object from json to array? My goal is to calculate percentage of each category of e. Below is my rough code snippet, I know it's missing many things like loop.Please help to complete it.

//some code for calling json, how to call I don't understand
var a0=[], a1=[], a2=[], a3=[];  //empty array for each category
      var e0=0, e1=0, e2=0, e3=0; //counter for each category

      if(e==0){
        e0++;
      }
      if(e==1){
        e1++;
      }
      if(e==2){
        e2++;
      }
      if(e==3){
        e3++;
      }
      var n= mydata.length; // calculate total no. of e's
      e0per= (e0/n) *100;
      e1per= (e1/n) *100;
      e2per= (e2/n) *100;
      e3per= (e3/n) *100;
      console.log(e0per);

Upvotes: 1

Views: 1693

Answers (1)

Gershom Maes
Gershom Maes

Reputation: 8170

data = {
    "mydata":[
         {
            "xvalue": "4 Oct 2015",
            "yvalue": 53,
                "e": 3
        }, {
            "xvalue": "5 Oct 2015",
            "yvalue": 67,
                "e": 3
        }, {
            "xvalue": "6 Oct 2015",
            "time":"1.00 PM",
                "yvalue": 99,
                "e": 2
        }, {
            "xvalue": "7 Oct 2015",
            "yvalue": 80,
                "e": 1
        }, {
            "xvalue": "8 Oct 2015",
            "yvalue": 160,
                 "e": 0
        }]
    };

// Here's the actual categorization part
categories = {};
for (var i = 0; i < data.mydata.length; i++) {
    var item = data.mydata[i];
    var e = item.e;
    if (!(e in categories)) categories[e] = [];
    categories[e].push(item);
}

console.log(categories)

The nice thing about this approach is that you don't need to worry about the different values the "e" index can have - a different list is created the first time a new unique value of "e" is discovered.

Upvotes: 1

Related Questions