Languages
[Edit]
EN

JavaScript - how to dynamically access object property with variable?

7 points
Created by:
Root-ssh
93380

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

  • dot notation, e.g. object.property
  • 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: ' + person.name + ', age: ' + person.age);

Output:

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).

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join