Weblurk
Weblurk

Reputation: 6802

How can I create Javascript object on the fly in a loop?

I'm looping through an array response and I want to put some values from it into an object data but my method below doesn't work ("data[i] is not defined").

var data = {},
    i = 0;

$(response).each(function(){
    data[i].title = response.title; // This does not work
    data[i].id = response.id;
    i++;
}

I want the resulting object data to look like this:

{
    0: {
          title: "First title",
          id: "First id"
       },

    1: {
          title: "Second title",
          id: "Second id"
       },
}

How can I achieve this?

Upvotes: 0

Views: 465

Answers (3)

epascarello
epascarello

Reputation: 207501

You are not referencing each index of the response, you are referencing properties off the array/object

$(response).each(function(index){
    data[i].title = response[index].title; 
    data[i].id = response[index].id;
    i++;
});

Upvotes: 1

Khanh TO
Khanh TO

Reputation: 48972

Try:

var data = {},
    i = 0;

$(response).each(function(){
    data[i] = {}; // Initialize an object first before assigning values: data[i] = {};.
    data[i].title = this.title; //Use this instead of response
    data[i].id = this.id;
    i++;
});

Upvotes: 1

hsz
hsz

Reputation: 152216

Just try with:

var data = [];

$(response).each(function(index, element){
    data.push({
        title: element.title,
        id:    element.id
    });
}

This snippet will create an array with object in it, so you can access them with:

data[0]; // [1], [2] ...

Upvotes: 0

Related Questions