1

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
2
  • You need a nested each function to reach the data you want. Commented May 8, 2015 at 18:01
  • 1
    Do the same thing you did in the inner loop. $.each(data, function(key, val) {} Commented May 8, 2015 at 18:02

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

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

Hope its help.

7 Comments

This looks like you just copied and pasted @John S's answer.
I started 10 minutes ago, bad luck for my. But i don't copy paste anything. Sory bad english.
5 min is enough time to review what others have answered. If you had a slightly different solution, or offered something else of value, I wouldnt downvote (possibly even upvote instead.) You should also explain (as John did) what it is about your answer that solves the problem - not just post code. For those reasons, and my initial comment, sorry, but I'm giving this a downvote.
Sorry for the answer, its my second or third, i will check the answers next time before posting it. No problem for the downvote, just explaining what i do.
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.