1

I have an object like this:

var items = {
  foobar: {
    foo: 'bar'
  }
}

and I have the name 'foobar' in a value I receive when the user selects it in a form, like this:

var item = $('select').val(); // which is 'foobar'

How can I access items.foobar.foo when I only know the name 'foobar' in that variable? It won't parse 'item' as a variable in items.item.foo...

I guess it's kinda like doing $items[$item]['foo'] in PHP, but I have no idea how do do it in Javascript.

Thanks.

Rob
  • 13
  • 2
  • Thanks everyone. I feel dumb now, don't know why I didn't try that. I guess I forgot there's an alternative to the dot notation. Since everyone gave me the correct answer, I'll just accept the oldest reply as the correct answer, just to be fair. But thanks! – Rob Sep 16 '11 at 13:07
  • possible duplicate of [javascript object, access variable property name?](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-name) ... [Using a variable as part of a javascript object property](http://stackoverflow.com/questions/4773897/using-a-variable-as-part-of-a-javascript-object-property) – user113716 Sep 16 '11 at 13:10

6 Answers6

1

You can directly access it by : items[foobar].foo

dhinesh
  • 4,676
  • 2
  • 26
  • 44
1

Having the name of the item you want in item, you access the property using squate brackets:

var item = "foobar";
alert(items[item].foo);
Jon
  • 428,835
  • 81
  • 738
  • 806
0

In JS it's very similar to PHP. foo['bar'] is identical to foo.bar, for example. Hence foo[something] will access the member of foo whose name is stored in something variable.

The bracket notation has the advantage of working for arbitrary keys, e.g. number and strings that contain non-alphanumerical characters.

Xion
  • 22,400
  • 10
  • 55
  • 79
0

yes, it will be items[ item ]['foo']; :)

c69
  • 19,951
  • 7
  • 52
  • 82
0

Well, I guess you could have tried your PHP suggestion:

items[item]['foo'];

or

items[item].foo;
pimvdb
  • 151,816
  • 78
  • 307
  • 352
0
var item = $('select').val(); // which is 'foobar'
var foo = items[item].foo;

or

var foo = items[item]['foo'];
duncan
  • 31,401
  • 13
  • 78
  • 99