0

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 :)

Jishnu V S
  • 8,164
  • 7
  • 27
  • 57
d33a
  • 690
  • 1
  • 14
  • 39
  • Yes it is possible to access them using position, but that would be bad way. Ideal way is `data[0].A` – Rajesh Nov 15 '16 at 06:33
  • to loop through this use Object.keys(obj[0]).forEach(function(key) { alert(obj[0][key]) }); – Geeky Nov 15 '16 at 06:33
  • 1
    Possible duplicate of [How do I loop through or enumerate a JavaScript object?](http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – 4castle Nov 15 '16 at 06:36
  • Using `async: false` is deprecated and in the process of being removed from jQuery. Use asynchronous calls instead. – 4castle Nov 15 '16 at 06:40
  • 1
    *I am new to json* Then you should start off by learning what JSON is, and is not. What you are talking about is a JavaScript array, **not** JSON. –  Nov 15 '16 at 07:27
  • `A`, `B` and `C` have no position. Properties in an object are unordered. –  Nov 15 '16 at 07:28

1 Answers1

3

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'
Keyur Shah
  • 536
  • 6
  • 20