Access object properties using computed property names
P粉578680675
P粉578680675 2023-08-20 15:32:14
0
2
496
<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粉578680675
P粉578680675

reply all(2)
P粉248602298

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

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