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粉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'})
P粉7558637502023-10-11 12:17:15
There are two ways to access properties Object:
something.bar
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)