JavaScript - how to dynamically access object property with variable?

7 points
Created by:

In JavaScript there are avaialble two ways to access object property:

  • dot notation, e.g.
  • square bracket notation, e.g. object['property']

1. Bracket notation property access example

// ONLINE-RUNNER:browser;

var object = {
    'key 1': {
        name: 'John',
        age: 25
    'key 2': {
        name: 'Kate',
        age: 32

var variable = 'key 2';
var person = object[variable];

console.log('name: ' + + ', age: ' + person.age);


name: Kate, age: 32

Note: using square bracket notation it is possile to use property characters that are not permited for dot notataion (inside above example space character has been used).

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.