access object property dynamically javascript code example
Example 1: javascript dynamically access object property
var person ={"first_name":"Billy","last_name":"Riley"};
var property_name="first_name";
alert(person[property_name]); //Dynamically access object property with bracket notation
Example 2: dynamic properties instead javascript
var foo = { pName1 : 1, pName2 : [1, {foo : bar }, 3] , ...}
var name = "pName"
var num = 1;
foo[name + num]; // 1
// --
var a = 2;
var b = 1;
var c = "foo";
foo[name + a][b][c]; // bar
Example 3: dynamic object property name javascript
let me = {
name: 'samantha',
};
// 1. Dot notation
me.name; // samantha
// 2. Bracket notation (string key)
me['name']; // samantha
// 3. Bracket notation (variable key)
let key = 'name';
me[key]; // samantha
Example 4: access object property dynamically javascript
let nestedObject = { levelOne: { levelTwo: { levelThree : 'final destination'} } }
const prop1 = 'levelOne';
const prop2 = 'levelTwo';
const prop3 = 'levelThree';
var destination = nestedObject[prop1][prop2][prop3];
// destination = 'final destination'