Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Basically I have a loop incrementing i, and I want to do this:

var fish = { 'fishInfo[' + i + '][0]': 6 };

however it does not work.

Any ideas how to do this? I want the result to be

fish is { 'fishInfo[0][0]': 6 };
fish is { 'fishInfo[1][0]': 6 };
fish is { 'fishInfo[2][0]': 6 };

etc.

I am using $.merge to combine them if you think why on earth is he doing that :)

share|improve this question
2  
What's wrong with either (a) just creating an array; or (b) using a loop to generate the counter? What is the problem you are having? –  Marcin Jan 6 '12 at 12:42
add comment

4 Answers

up vote 7 down vote accepted

Declare an empty object, then you can use array syntax to assign properties to it dynamically.

var fish = {};

fish[<propertyName>] = <value>;
share|improve this answer
1  
Cheers this sorted it. And I needed $.extend instead of $.merge :) –  SLC Jan 6 '12 at 13:17
add comment

Do this:

var fish = {};
fish['fishInfo[' + i + '][0]'] =  6;

It works, because you can read & write to objects using square brackets notation like this:

my_object[key] = value;

and this:

alert(my_object[key]);
share|improve this answer
add comment

For any dynamic stuff with object keys, you need the bracket notation.

var fish = { };

fish[ 'fishInfo[' + i + '][0]' ] = 6;
share|improve this answer
add comment

Multidimensional Arrays in javascript are created by saving an array inside an array.

Try:

var multiDimArray = [];
for(var x=0; x<10; x++){
    multiDimArray[x]=[];
    multiDimArray[x][0]=6;
}

Fiddle Exampe: http://jsfiddle.net/CyK6E/

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.