6

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 :)

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • 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 06 '12 at 12:42

4 Answers4

10

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

var fish = {};

fish[<propertyName>] = <value>;
nikc.org
  • 16,462
  • 6
  • 50
  • 83
5

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]);
Tadeck
  • 132,510
  • 28
  • 152
  • 198
2

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

var fish = { };

fish[ 'fishInfo[' + i + '][0]' ] = 6;
jAndy
  • 231,737
  • 57
  • 305
  • 359
0

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/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189