Gabriel Santos
Gabriel Santos

Reputation: 4974

Variable manipulation

I have the follow sample code:

type = 'Foo';

test = {
    type: {
        'fooVal': 'bar'
    }
}

alert(test.type.fooVal); // Bar
alert(test.Foo.fooVal); // TypeError: teste.Foo is undefined

How I can get the second alert to work?

I've tried:

test = {
    '"' + type + '"': {
        'fooVal': 'bar'
    }
}

But doesn't work.

Upvotes: 0

Views: 164

Answers (3)

Lloyd
Lloyd

Reputation: 29668

You don't have a property called Foo you have a property called type. You need to do something like this:

type = 'Foo';

test = {};
test[type] = {
    'fooVal': 'bar'
};

alert(test.type.fooVal); // Bar
alert(test.Foo.fooVal); // TypeError: teste.Foo is undefined

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187034

You can't use an object literal if the key is defined by a variable.

type = 'Foo';

test = {};
test[type] = {
  fooVal: 'Bar'
};

alert(test.Foo.fooVal);  // Bar

[] on objects lets you access a property dynamically, for setting or getting.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

Use bracket notation to do the assignment instead:

type = 'Foo';
test = {};
test[type] = {fooVal: 'bar'};
alert(test.Foo.fooVal);

You can't use variables as keys when assigning via object notation.

Upvotes: 4

Related Questions