简体   繁体   中英

Iterating through a json array of objects using jquery

I know this may seem basic to some of you, but I am trying to iterate a json object. I apologize as I seem to be having difficulty getting various examples to work. I've also read the jQuery documentation and the json examples listed there don't quite match my json structure.

Here's a link to my example which is displaying "null" in the console where I expected to see "1". I'm just trying to print out the article_id element of each "node" in the json array.

http://jsfiddle.net/zZjfj/1/

var json = [
    [{
        "article_id": 1,
            "article_title": "test",
            "article_content": "test1"
    }, {
        "article_id": 2,
            "article_title": "test2",
            "article_content": "this is a second test article"
    }]
];

$.each(json, function (arrayID, group) {
    console.log(group.article_id);
});

Your json is not an array of object, it is an array of array of object .

When you enter in your iteration, for each element, the arrayID is the index (0, 1, etc...) and the group is the sub array.

To solve your problem, use json[0] instead of json in your code

$.each(json[0], function (arrayID, group) {
    console.log(group.article_id);
});

Your object 'json' is an array with 1 element, which is itself an array of 2 elements. If your change your example to:

var json = [
    { "article_id": 1,
      "article_title": "test",
      "article_content": "test1" },
    { "article_id": 2,
      "article_title": "test2",
      "article_content": "this is a second test article" }
  ];

Then it produces the articles ids: 1,2.

If you need to iterate over a two dimensional array, then you can use a nested loop:

$.each(json, function (idx1, entry) {
  $.each(entry, function (idx2, group) {
      console.log(group.article_id);
  });
});

You have an array nested inside of another array. You may want to take a look at how your JSON is being output, but in the meantime it's solved easily by another level of iteration:

$.each(json, function (arrayID, group) {
    $.each(group, function (arrayID, group) {
        console.log(group.article_id);
    });
});

http://jsfiddle.net/zZjfj/2/

I've created a script that will allow you to see paths to values in JSON as well: http://jsfiddle.net/ExplosionPIlls/zEBZr/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM