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
  • 48,897
  • 65
  • 188
  • 331
  • 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
  • 15,738
  • 6
  • 46
  • 82
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
  • 125,377
  • 26
  • 148
  • 197
2

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

var fish = { };

fish[ 'fishInfo[' + i + '][0]' ] = 6;
jAndy
  • 223,102
  • 54
  • 301
  • 354
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
  • 90,944
  • 18
  • 150
  • 184