search

Home  >  Q&A  >  body text

Access object properties using computed property names

<p>I am trying to access the properties of an object using dynamic names. Is this possible? </p> <pre class="brush:php;toolbar:false;">const something = { bar: "Foobar!" }; const foo = 'bar'; something.foo; // The idea is to access something.bar and get "Foobar!"</pre> <p><br /></p>
P粉578680675P粉578680675492 days ago506

reply all(2)I'll reply

  • P粉248602298

    P粉2486022982023-08-21 11:40:18

    This is my solution:

    function resolve(path, obj) {
        return path.split('.').reduce(function(prev, curr) {
            return prev ? prev[curr] : null
        }, obj || self)
    }

    Usage example:

    resolve("document.body.style.width")
    // 或者
    resolve("style.width", document.body)
    // 或者甚至使用数组索引
    // (someObject已在问题中定义)
    resolve("part.0.size", someObject) 
    // 当中间属性未定义时返回null:
    resolve('properties.that.do.not.exist', {hello:'world'})

    reply
    0
  • P粉242126786

    P粉2421267862023-08-21 09:38:46

    There are two ways to access object properties: Dot notation : something.bar and square bracket notation: something['bar'].

    The value in the square brackets can be any expression. Therefore, if the property name is stored in a variable, square bracket notation must be used:

    var something = {
      bar: 'foo'
    };
    var foo = 'bar';
    
    // both x = something[foo] and something[foo] = x work as expected
    console.log(something[foo]);
    console.log(something.bar)

    reply
    0
  • Cancelreply