Javascript – Dynamically access object property using variable


I'm trying to access a property of an object using a dynamic name. Is this possible?

const something = { bar: "Foobar!" };
const foo = 'bar';; // The idea is to access, getting "Foobar!"

Best Solution

There are two ways to access properties of an object:

  • Dot notation:
  • Bracket notation: something['bar']

The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:

var something = {
  bar: 'foo'
var foo = 'bar';

// both x = something[foo] and something[foo] = x work as expected