开发者

JavaScript - array of objects, etc

开发者 https://www.devze.com 2023-04-05 19:49 出处:网络
Say I have the following: var a = \'1\',开发者_如何学Python b = \'foo\'; How do I create an object using the above variables such that my object looks like this:

Say I have the following:

var a = '1',开发者_如何学Python
    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.


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


var obj = { '1' : 'foo' };

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

or

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号