Africa Matji
Africa Matji

Reputation: 385

Jquery loop through Json with array of objects and get key name

I am able to read a json array from php, i want to display the key name of the items aswell. This might not make sense now but please check below code.

My json data

{ "A":{"Africa":"201455632", "Asia":"5145000"}, 
  "B":{"Brasil":"68455222"},
  "C":{"China":"14546787"}
 }



My js code i am able to dislplay the key-val pair

 $.each(data, function() {
     console.log('---')
     $.each(this, function(k, v) {
      console.log(k, v)
     });
 });

Its displays like this

  ---
  Africa 201455632
  Asia 5145000 
  ---
  Brasil 68455222 
  ---
  China 14546787

My Problem is, i want to display it like this, with their key name aswell, what can i replace console.log('---') with

A
  Africa 201455632
  Asia 5145000
B
  Brasil 68455222
C
  China 14546787

Upvotes: 1

Views: 912

Answers (2)

Juan Marcos Armella
Juan Marcos Armella

Reputation: 737

$.each(data, function(key, value) {
     console.log(key)
     $.each(value, function(k, v) {
      console.log(k, v)
     });
 });

Hope its help.

Upvotes: 0

John S
John S

Reputation: 21482

Use the parameters to the callback function (just like you did with the inner loop).

$.each(data, function(key, value) {
    console.log(key);
    $.each(value, function(k, v) {
        console.log('  ' + k, v);
    });
});

jsfiddle

Upvotes: 5

Related Questions