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

1
  • 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? Commented Jan 6, 2012 at 12:42

4 Answers 4

10

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

var fish = {};

fish[<propertyName>] = <value>;
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers this sorted it. And I needed $.extend instead of $.merge :)
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]);

Comments

2

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

var fish = { };

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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.