Access object properties using dynamically computed names
P粉419164700
P粉419164700 2023-10-10 22:06:30
0
2
644

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粉419164700
P粉419164700

reply all(2)
P粉098979048

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'})
P粉755863750

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template