-3

I want to iterate this kind of JSON:

{
  "object": {
    "array1": {
      "id": 1
    },
    "array2": {
      "id": 2
    }
  }
}

I've attempted to use this:

for (var i in dictionary) {
  console.log(dictionary[i].id);
}

but doesn't work.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
decryptable
  • 33
  • 1
  • 9

3 Answers3

3

I've searched everywhere and can't find an answer that I want. Seriously? Didn't see what $.each does?

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

var arr = {
  "object": {
    "array1": {
      "id": 1
    },
    "array2": {
      "id": 2
    }
  }
};
$.each(arr, function (i, v) {
  console.log(i);
  console.log(v);
  $.each(v, function (idx, val) {
    console.log(idx);
    console.log(val);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

AJAX

If you are using AJAX to fetch the JSON, you can very well use: $.getJSON:

$.getJSON("https://cdn.rawgit.com/fge/sample-json-schemas/master/avro/avro-schema.json", function (res) {
  $.each(res, function (i, v) {
    console.log(i);
    console.log(v);
    if (typeof v == "object")
    $.each(v, function (idx, val) {
      console.log(idx);
      console.log(val);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
-1
var objectData = {
  "object": {
    "array1": {
      "id": 1
    },
    "array2": {
      "id": 2
    }
  }
};

$.each(objectData, function(key, data){
    // Do stuff here
});

To use this with json from a URL:

$.ajax({
    url: URL,
    dataType: 'jsonp',
    success: function(json) {
       $.each(json, function(key, data){
           console.log(key);
           console.log(data);
        });
    }
});
Craig
  • 332
  • 1
  • 7
-1

try the following

var d={
  "object": {
    "array1": {
      "id": 1
    },
    "array2": {
      "id": 2
    }
  }
}

$.each(d,function(i,v){console.log(i,v)})
Ram Singh
  • 6,664
  • 35
  • 100
  • 166
vakho papidze
  • 465
  • 3
  • 12