Dynamically access object property using variable
There are two ways to access properties of an object:
- Dot notation:
something.bar
- Bracket notation:
something['bar']
The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:
var something = { bar: 'foo'};var foo = 'bar';// both x = something[foo] and something[foo] = x work as expectedconsole.log(something[foo]);console.log(something.bar)
This is my solution:
function resolve(path, obj) { return path.split('.').reduce(function(prev, curr) { return prev ? prev[curr] : null }, obj || self)}
Usage examples:
resolve("document.body.style.width")// orresolve("style.width", document.body)// or even use array indexes// (someObject has been defined in the question)resolve("part.0.size", someObject) // returns null when intermediate properties are not defined:resolve('properties.that.do.not.exist', {hello:'world'})
In javascript we can access with:
- dot notation -
foo.bar
- square brackets -
foo[someVar]
orfoo["string"]
But only second case allows to access properties dynamically:
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