Novkovski Stevo Bato
Novkovski Stevo Bato

Reputation: 1043

Array inside json array

I got result like

{"ID":1022,"Type":"type1","Name":"name1","Values":[{"ID":3540,"Name":"1"},{"ID":3541,"Name":"2"},{"ID":3542,"Name":"cb"}]}

so on success i got function like this

   success: function(data) {
            $.each(data, function() {
                $('#properties').append(
                this.ID + "," +
                this.Name + "," +

                this.type + "," +
                    this.values
                );
            });
        }

but "values" is another array, so how to show it?

Upvotes: 0

Views: 151

Answers (4)

webnoob
webnoob

Reputation: 15934

I believe this.Values[0].ID should return the ID from the first element correctly.

You could also loop through each item in the array and access it in the same way.

for (var i = 0; i < this.Values.length; i++) {
    alert(this.Values[i].ID); //Show an alert for each ID.
}

Upvotes: 1

Herbert
Herbert

Reputation: 5645

I am not quite sure what the value of this is inside the inner-most function, but it is probably not what you want it to be. In order to pass a variable to a function when it is created, instead of when it is called, you should wrap it with another function like this:

{
    success: function(data) {
        $.each(data, (function(dat) { return function(index, value) {
            $('#properties').append(
               value.ID + "," +
               value.Name + "," +
               dat.type + "," +
               dat.values
            );
        }; ) (data));
    }
};

Upvotes: 0

Bilal lilla
Bilal lilla

Reputation: 658

//get the total length of values array.
this.Values.length;

for (  var i = 0 ; i < this.Values.length; i++ ){
 var resultId= this.Values[i].ID;
 var resultName = this.Values[i].Name;
}

This works.

Upvotes: 1

JohnHoulderUK
JohnHoulderUK

Reputation: 679

this.values[0].ID may work, however, I'm not completely sure. I guess there's no harm in trying, though.

Upvotes: 0

Related Questions