d33a
d33a

Reputation: 740

How to traverse through a JSON array?

I am new to json and arrays and objects. So this may be a very trivial doubt. I have an array of the structure:

[{
"A": {"key11": 10, "key12": 20, "key13": 30},
"B": {"key21": 10, "key22": 20},
"C": {"key31": 10, "key32": 20, "key33": 30, "key34": 40}
}]

I am accessing the data via an ajax call:

$.ajax({
    url : 'somepath/fileName.json',
    dataType : 'json',
    async : false,
    type : 'get',
    success : function(data) 
      {
       MyData = data;
      },
    error : function() {
       alert("error");
      }
});

Now my MyData contains an Object of the above mentioned data. I need to access A,B,C but my question is whether its possible to access them using positions? Kindly help. Thanks :)

Upvotes: 0

Views: 739

Answers (1)

Keyur Shah
Keyur Shah

Reputation: 536

As per your question title this is how you traverse through your JavaScript Array using $.each

var data = [{
    "A": {
      "key11": 10,
      "key12": 20,
      "key13": 30
    },
    "B": {
      "key21": 10,
      "key22": 20
    },
    "C": {
      "key31": 10,
      "key32": 20,
      "key33": 30,
      "key34": 40
    }
  }];


$.each(data, function() {
    $.each(this, function(outerkey, outervalue) {
        console.log(outerkey);
        $.each(this, function(innerkey, innervalue) {
            console.log(innerkey + '=' + innervalue);
        });
    });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JSON Traverse</title>
</head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<body>
</body>
</html>

If you only want to access Key (A,B,C)

$.each(first, function(key, value) {
    $('#results').append("  " + key + " ");
});

If you want a specific key and you know the index then you can use Object aswell

var result = Object.keys(data[0]); 
console.log(result[0]); //this will return 'A'

Upvotes: 3

Related Questions