-1

Say I have the following:

var a = '1',
    b = 'foo';

How do I create an object using the above variables such that my object looks like this:

'1' => 'foo'

I'm trying to make this like an associative array. Furthermore, I want 1 to contain an array of objects. I have the variable that have the array of object; I just need to put it in 1.

3 Answers 3

4

Use an object literal:

var myObject = { "1" : "foo" };

or, if you want to create it from variables, create a new object then assign things.

var myObject = {};
myObject[a] = b;

Furthermore, I want 1 to contain an array of objects

JavaScript doesn't care what type the data is. b can be an array as easily as a string. (And you can use an array literal where you have a string literal in the short version)

var myObject = { "1" : [ 7, "foo", new Date() ] };
Sign up to request clarification or add additional context in comments.

4 Comments

+1 for posting almost exactly what I'd just typed (but obviously no longer need to post).
Keep in mind that a Javascript array is basically an object as well. So, if var testArray = [];, you can manipulate it with the form testArray[0] = 1; or testArray['1'] = 'foo'; or even testArray.bar = 'baz';.
Quentin, I'm having problems assigning an object to a property in my containing object. For example: oMyTest['1']['data'] = data;. The variable data is an object.
So long as oMyTest['1'] is an object, that should just work.
0
var obj = { '1' : 'foo' };

obj['1']; // returns 'foo'

or

var obj = { '1' : new Array() };
obj['1']; // returns an array

1 Comment

It sounds the OP wants the mirror image of the second obj, which I doubt would be possible.
0

To do literally what you asked:

var a = '1',
    b = 'foo',
    o = {};

o[a] = b;

Quentin has the rest of the answer.

Edit

An example of assigning an object to an object property:

var foo = {bar: 'baz'};
var obj = {foo: foo};

// or 
// var obj = {};
// obj['foo'] = foo;
// or
// obj.foo = foo;

alert(obj.foo.bar); // baz

1 Comment

RobG, I need o to contain another object. Say I have the object data and want it in o['data'] - how do I do that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.