user2415277
user2415277

Reputation: 11

How do I loop this using jQuery

I am not lying I am a beginner. So here is my issue. I am receiving a json object in an ajax request and would like to loop its content. I need to create the loop and gather data within the variable "pins."

function(data) {

                   var pins = [
                                   {
                                        "lat":      data.lat,
                                        "lon":      data.lon,
                                        "imageURL": data.imageURL,
                                        "title":    data.title,
                                        "subTitle": data.subTitle,
                                        "pinColor": data.pinColor,
                                        "selected": data.selected,
                                        "pinImage": data.pinImage,
                                        "index":    data.index
                                    }
                               ];
         }

Data is an object and I would like to loop every single element using jQuery.

Thanks

Upvotes: 1

Views: 64

Answers (3)

Kyle
Kyle

Reputation: 2872

The following should work to iterate over data to collect the desired attributes from each object in the array and construct pins.

function(data) {
    var pins = [];

    for (var i=0; i < data.length; i++) {
        var new_pin = {
            "lat":      data[i].lat,
            "lon":      data[i].lon,
            "imageURL": data[i].imageURL,
            "title":    data[i].title,
            "subTitle": data[i].subTitle,
            "pinColor": data[i].pinColor,
            "selected": data[i].selected,
            "pinImage": data[i].pinImage,
            "index":    data[i].index
        };

        pins.push(new_pin);
    }
}

Upvotes: 0

Tomas Kirda
Tomas Kirda

Reputation: 8413

$.each({ a: 1, b: 2}, function(key, value){
    console.log(key, value);
});

Upvotes: 1

h2ooooooo
h2ooooooo

Reputation: 39550

This is a javascript array with an object inside, and has nothing to do with jQuery (nor should you use jQuery to loop through it).

for (var i = 0; i < pins.length; i++) {
    console.log(pins[i].lat);
    console.log(pins[i].lon);
    console.log(pins[i].imageURL);
    //etc
}

Upvotes: 1

Related Questions