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!"
There are two ways to access properties of an object:
something.bar
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)
careful with this: javascript compilers will error here since they dont rename strings but they do rename object properties
Some more info on why this is possible: JS objects are associative arrays, that's why. Further Reading: quirksmode.org/js/associative.html stackoverflow.com/questions/14031368/…
@dotnetguy No they are not. Arrays are objects that inherit from the plain JS object prototype and therefore you can add properties a go-go like any plain object. The 'associative' behaviour is more object-like than array like. You can't iterate the 'associative' version by simple index so it is not displaying array-like behaviour. You can define your 'associative' array as {} or [] and treat it the same in either case as far as random property access is concerned.
@VanquishedWombat Not sure what your objection pertains to? I did not say that JS Objects are arrays?
as a reference to the correct answer , Reference