NibblyPig
NibblyPig

Reputation: 52932

How can I create a javascript associative array { } with dynamic key names?

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

Upvotes: 6

Views: 14614

Answers (4)

Tadeck
Tadeck

Reputation: 137320

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]);

Upvotes: 5

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

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/

Upvotes: 0

nikc.org
nikc.org

Reputation: 16952

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

var fish = {};

fish[<propertyName>] = <value>;

Upvotes: 10

jAndy
jAndy

Reputation: 235982

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

var fish = { };

fish[ 'fishInfo[' + i + '][0]' ] = 6;

Upvotes: 2

Related Questions