Dynamically access object property using variable

I'm trying to access a property of an object using a dynamic name. Is this possible?

const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"

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 foo = 'bar';
    something[foo];
    // both x = something[foo] and something[foo] = x work as expected
    

    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")
    // or
    resolve("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] or foo["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
    
    链接地址: http://www.djcxy.com/p/31890.html

    上一篇: 在C#中包装COM对象/动态类型

    下一篇: 使用变量动态访问对象属性