开发者

Using $.each for more complex JSON data

I understand how to use $.each to go through JSON data which looks like this:

{
    "one": "Singular sensation",
    "two": "Beady little eyes",
    "three": "Little birds pitch by my doorstep"
}

For example:

$.each(data, function(key, val) {
    echo '<div>' + val + '-' + key + '</div>';
});

But how do I use $.each to go though JSON data which looks like this:

{
    "d": [
        {
            "__t开发者_如何转开发ype": "Tab",
            "id": 1,
            "name": "Innovation",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 3,
            "name": "Thought",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 0,
            "name": "Collaboration",
            "ordering": 0
        }
    ]
}

Where I want to use the id and name.


Use this:

var complex_data = {
    "d": [
        {
            "__type": "Tab",
            "id": 1,
            "name": "Innovation",
            "ordering": 0
        },
         ...
    ]
}

//Use:
$.each(complex_data.d, function(i, val){
    //The following properties can be used in your code:
    val.id;
    val.name;
    //And also: val.__type, val.ordering
});

If your complex_data contains more keys like d, use:

$.each(complex_data, function(i, val){
    $.each(val, function(j, val){
        //The following properties can be used in your code:
        val.id;
        val.name;
        //Also: val.__type, val.ordering
    });
});


Same way

$.each(data, function(key, val) {
    $.each(val, function(index, val2){
      console.log(val2.name);
    });
});


$.each(data.d, function(index, val) {
    echo '<div>' + val.id + '-' + val.name + '</div>';
});


Well this code is fairly specific to your example so it might need a little tweaking, but you could do it like this:

data = {
    "d": [
        {
            "__type": "Tab",
            "id": 1,
            "name": "Innovation",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 3,
            "name": "Thought",
            "ordering": 0
        },
        {
            "__type": "Tab",
            "id": 0,
            "name": "Collaboration",
            "ordering": 0
        }
    ]
}

$.each(data.d, function(key, val) {
    $('#data').append('id: ' + val.id + ', name: ' + val.name + '<br />');
});

http://jsfiddle.net/Uxguf/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜