How to access js object element as variable name?
- User
How to access js object element as variable name?
Assistant
Accessing JavaScript Object Elements Using Variable Names
In JavaScript, you can access object properties using variable names in several ways:
1. Bracket Notation
The most common way to access an object property using a variable is with bracket notation:
const obj = { name: 'John', age: 30, city: 'New York' }; const propName = 'name'; console.log(obj[propName]); // Output: 'John'2. Dynamic Property Access
You can use any expression inside the brackets:
const obj = { 'first-name': 'John', 'last-name': 'Doe' }; const prefix = 'first'; const property = prefix + '-name'; console.log(obj[property]); // Output: 'John'3. Computed Property Names (ES6)
When creating objects, you can use computed property names:
const key = 'dynamicKey'; const value = 'dynamicValue'; const obj = { [key]: value }; console.log(obj.dynamicKey); // Output: 'dynamicValue'4. Accessing Nested Properties
For nested objects, you can chain bracket notation:
const obj = { user: { name: 'John', address: { city: 'New York' } } }; const path = ['user', 'address', 'city']; let result = obj; path.forEach(key => { result = result[key]; }); console.log(result); // Output: 'New York'Important Notes
- If the property name contains spaces or special characters, you must use bracket notation
- Dot notation (obj.property) only works with literal property names
- If the variable doesn't match any property, it returns
undefined
Would you like me to explain any of these methods in more detail?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.