HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Accessing an object property with a dynamically-computed name

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertywithobjectnamedynamicallyaccessingcomputed

Problem

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

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

Solution

There are two ways to access properties of an object:

  • Dot notation: something.bar



  • 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
console.log(something[foo]);
console.log(something.bar)

Context

Stack Overflow Q#4244896, score: 1307

Revisions (0)

No revisions yet.