How to Access JavaScript Object Properties Dynamically?

Object property names can be accessed dynamically only using the bracket notation, without using quotes:

const obj = { foo: 'bar' };
const dynamicPropName = 'foo';

console.log(obj[dynamicPropName]); // 'bar'

You can also use JavaScript template literal string interpolation to achieve the same. This is especially useful if the property name is partially known already. For example:

const obj = { fooBar: 'baz' };
const dynamicPropName = 'foo';

console.log(obj[`${dynamicPropName}Bar`]); // 'baz'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.