Say I have something that looks like this in javascripts:
var obj = {
subObj : {}
};
var type = 'subObj';
How can I get obj's
subObj
w/ type
? For instance I would like to do something like:
obj.(type);
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!
obj[type]
You use subscript notation.
Properties are accessed by name, using either the dot notation:
MemberExpression . IdentifierName
CallExpression . IdentifierName
or the bracket notation:
MemberExpression [ Expression ]
CallExpression [ Expression ]
You can treat objects like associative arrays in JavaScript, so you'll be able to access the inner object like:
var obj = {
subObj : {}
};
var type = "subObj";
var subObj = obj[type];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With