ahmad.ideveloper ahmad.ideveloper - 1 month ago 6
Javascript Question

loop over object with jQuery.each()

I have an json object in this format

var data = [
{ "label" : "January" }, { "value" : 10 }, { "barcolor" : "rgba(128, 0, 0, 0.9)" },
{ "label" : "February" }, { "value" : 20 }, { "barcolor" : "rgba(0, 128, 0, 0.9)" },
{ "label" : "October" }, { "value" : 100 }, { "barcolor" : "rgba(0, 0, 128, 0.9)" },
{ "label" : "November" }, { "value" : 80 }, { "barcolor" : "rgba(255, 0, 0, 0.9)" },
{ "label" : "December" }, { "value" : 20 }, { "barcolor" : "rgba(0, 255, 0, 0.9)" },
{ "label" : "January" }, { "value" : 70 }, { "barcolor" : "rgba(0, 0, 255, 0.9)" }
];


I want to print in combine format like

<h1 style="color:rgba(128, 0, 0, 0.9)">January <em>count: 10</em></h1>


these should be 6 h1 or whatever no of "Label",
BUT MY jQuery going 18 in a loop

$.each(data, function(index, val) {
//console.log('index : ' + index + ' || val : ' + val.label);
$.each(val, function(i, v) {
//console.log('i : ' + i + ' || v : ' + v);
var dhtml = '<h1 style="color:' + val.barcolor + '">' + val.label + '<em>' + val.value + '</em></h1>'
$('body').append(dhtml);
});
});


not getting desired output
http://codepen.io/iahmad/pen/BLgJBb

Answer

You should change your JSON format and loop, here is working JS (copy to codepen):

var data = [
    { "label" : "January", "value"  : 10, "barcolor" : "rgba(128, 0, 0, 0.9)" },
    { "label" : "February", "value"  : 20, "barcolor" : "rgba(0, 128, 0, 0.9)" },
    { "label" : "October", "value"  : 100, "barcolor" : "rgba(0, 0, 128, 0.9)" },
    { "label" : "November",  "value"  : 80, "barcolor" : "rgba(255, 0, 0, 0.9)" },
    { "label" : "December", "value"  : 20,  "barcolor" : "rgba(0, 255, 0, 0.9)" },
    { "label" : "January", "value"  : 70,  "barcolor" : "rgba(0, 0, 255, 0.9)" }
];

$.each(data, function(i, val) {
    var dhtml = '<h1 style="color:' + val.barcolor + '">' + val.label + '<em>' + val.value + '</em></h1>'
    $('body').append(dhtml);
});
Comments