Languages
[Edit]
EN

JavaScript - how to dynamically access object property with variable?

7 points
Created by:
Root-ssh
68370

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
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join