Home  >  Q&A  >  body text

Access object properties using dynamically computed names

I'm trying to access the properties of an object using dynamic names. is it possible?

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


P粉419164700P粉419164700375 days ago590

reply all(2)I'll reply

  • P粉098979048

    P粉0989790482023-10-11 12:39:43

    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")
    // 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'})

    reply
    0
  • P粉755863750

    P粉7558637502023-10-11 12:17:15

    There are two ways to access properties Object:

    • Dot symbol: something.bar
    • Bracket notation: something['bar']

    The value inside the brackets can be any expression. Therefore, if the property name is stored in a variable, 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