0

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?

2
  • Look at the documentation for jQuery each() Commented Dec 19, 2013 at 14:00
  • You need to learn more about the difference between arrays and objects. Commented Dec 19, 2013 at 14:04

3 Answers 3

1

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++;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but why use this instead of response? Any differences in the outcome?
@Weblurk: this is current item in the loop while response is your array
1

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++;
});

Comments

0

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] ...

1 Comment

Probably because the structure is not consistent with what the OP asked. Equally response.title doesn't refer to the item in each iteration of the .each() loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.