Kate Wintz
Kate Wintz

Reputation: 643

Get output json in $.each

My json data is this:

{
   "guide":0,
   "reunits":[
      {
         "residence":[
            {
               "name_re":"THE PORT",
               "id":"88aa355ca54853640929c25c33613528"
            }
         ]
      },
      {
         "residence":[
            {
               "name_re":"KECIK",
               "id":"2843543fa45857d92df3de222938e84a"
            }
         ]
      },
      {
         "residence":[
            {
               "name_re":"GREEN ANKA",
               "id":"fe585cc4b4dfff1325373728929e8af9"
            }
         ]
      }
   ]
}

How can done alert, value name_re or id in json data above by each in jquery?

My try:

$.each(data.reunits, function (index, value) {
    alert(value.residence.name_re); // this don't output.
})

Upvotes: 4

Views: 132

Answers (5)

kvc
kvc

Reputation: 1137

residence is an array ,so you have to do the following js fiddle

    $(document).ready(function() {
        var data = {
            "guide": 0,
            "reunits": [
                {
                "residence": [
                    {
                    "name_re": "THE PORT",
                    "id": "88aa355ca54853640929c25c33613528"}
                ]},
            {
                "residence": [
                    {
                    "name_re": "KECIK",
                    "id": "2843543fa45857d92df3de222938e84a"}
                ]},
            {
                "residence": [
                    {
                    "name_re": "GREEN ANKA",
                    "id": "fe585cc4b4dfff1325373728929e8af9"}
                ]}
            ]
        };
        $.each(data.reunits, function() {
            $.each(this.residence, function() {
                alert(this.name_re);
                alert(this.id);
            });
        });
    });

Upvotes: 1

Fatih Acet
Fatih Acet

Reputation: 29529

var data = JSON;
var reunits = data.reunits;
for (var i = 0, len = reunits.length; i < len; i++) {
    alert(reunits[i].residence[0].name_re);
}

Upvotes: 0

kapa
kapa

Reputation: 78671

residence is an array ([]), which has only one element, an object that has a name_re attribute.

alert(value.residence[0].name_re);

jsFiddle Demo

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227240

value.residence is an array. It should be value.residence[0].name_re.

$.each(data.reunits, function (index, value) {
    alert(value.residence[0].name_re);
})

Upvotes: 0

Ry-
Ry-

Reputation: 224904

It's because they're within arrays. You need to access index 0 for each of them:

$.each(data.reunits, function(index, value) {
    alert(value.residence[0].name_re);
});

Upvotes: 2

Related Questions