3

dont laugh think im having a long day work blonde moment as im a bit out of practice with JS. Any helped appreciated for what I think is a stupidly simple problem.

optionarray = [];

for(i=0;i<response.length;i++) {

    optionarray[i]['content'] = response[i]['name'];
    optionarray[i]['value'] = response[i]['id'];
}

I keep getting optionarray[i] is undefined when trying to add it to the array and build it. I know im doing something ridiculously stupid I just can't remember what :)

Many thanks for any help in advance.

1
  • Thank you everyone for your help. I was being dumb :) Thinking too much the PHP way ;) Commented Sep 15, 2011 at 20:34

4 Answers 4

3
optionarray = [];

for(i=0;i<response.length;i++) {

    optionarray[i] = {
            'content' :response[i]['name'], 
            'value': response[i]['id']
    };

}
Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to access properties of optionarray[i], which does not exist.

What you should be doing in each iteration is

  1. adding a new object to optionarray
  2. setting that object's properties

You can do both at once like this:

optionarray = [];

for(i=0;i<response.length;i++) {
    optionarray.push({
        content: response[i]['name'],
        value: response[i]['id']
    });
}

3 Comments

I like this solution better than mine, but I think it's "push" and not "push_back"
@PhilParsons: Ooops! C++ bug there :) -- fixed.
ha, yeah often find myself doing similar. And this is the best approach in my opinion. Although I don't see the point of moving the data from one array to another (perhaps I am missing the bigger picture!)
1

I think you just need to initialize the optionarray[i] object within your for loop:

var optionarray = []; //NOTE: I added var here so because otherwise it's an implicit global

for(i=0;i<response.length;i++) {
    optionarray[i] = {};
    optionarray[i]['content'] = response[i]['name'];
    optionarray[i]['value'] = response[i]['id'];
    // BETTER: optionarray.push({content: response[i]['name'], value: response[i]['id']});
}

if I'm not mistaken.

1 Comment

Thanks for your help much appreciate ;-)
0

Try this one

optionarray[i] = [];
optionarray[i]['content'] = response[i]['name'];     
optionarray[i]['value'] = response[i]['id']; 

You need to define optionarray[i] as array first

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.