1

Im kind of lost at reading data inside a JSON object, here's the JSON i have:

var data = [
          {"mes":{
                  "January":{
                     "Inversion":"1000","Fans":"1020"}
                            }
                 },
           {"mes":{
                 "February":{
                     "Inversion":"15500","Fans":"285"}
                            }
            }
            ]

I want to be able to print like:

January,1000,1020

February,15500,285

Thanks!

Alejandro Figueroa
  • 419
  • 1
  • 4
  • 14

3 Answers3

0
for (var i = 0; i < data.length; i += 1) {
  obj = data[i].mes;
  for (key in obj) {
    if(obj.hasOwnProperty(key)) {
      var monthName = key;
    }
  }
  var iv = obj[monthName].Inversion;
  var fans = obj[monthName].Fans;
  console.log( monthName + "," + iv + "," + fans);
}

Working example: http://jsfiddle.net/sXtZk/

veddermatic
  • 1,082
  • 7
  • 15
0
// initialise variable to build output
var out = []

// loop through the array
for(var i=0;i < data.length; i++){

    // get a reference to the inner object
    var item = data[i].mes

    // loop through the inner object (k is the key name)
    for(k in item){
        // push the built up string onto the output array
        out.push(k+", "+item[k].Inversion+", "+item[k].Fans)
    }
}

// display the output, joining with newlines
console.log(out.join("\n"))
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
0

At the heart of it, JSON really is just a formal way of combining basic ol' JS arrays and objects to make an object which can be interchanged across servers and parsed readily.

So, how do you iterate over an array?

for (i=0; i<array.length; i++) 
    fn(array[i]);

What about enumerating the values in a JS object/map?

for ( key in obj )
    fn(obj[key]);

Let's try putting those together then:

for (var i=0; i < data.length; i++) {

    for ( var key in data[i]["mes"] ) {
        var mName = key;
        var inversion = data[i]"mes"][key]["Inversion"];
        var fans = data[i]"mes"][key]["Fans"]
        alert( [mName, inversion, fans].join(", "));
    }
}

I will add, though, that your JSON structure is rather poor. On every level you have mes as a key corresponding to an object, which is unduly doubly nested. In that scenario, mes has no real meaning. Consider, instead, this structure:

var data = [
    {
        "mes": "January",
        "Inversion": "1000",
        "Fans": "1020"
    },
    {
        "mes": "February",
        "Inversion": "15500",
        "Fans": "285"
    }
];

This is simpler, and more logical, and (as you'll find) easier to work with:

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

    for ( var key in data[i] ) {
        objToString.push(data[i][key]);
    }

    alert( objToString.join(", "));
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66