In JavaScript, you can access an object's elements (properties) in several ways, depending on whether you know the property name at the time of writing the code or if it's determined dynamically at runtime. Here are the common methods:
1. Dot Notation (Known Property Name)
If you know the property name ahead of time, you can use dot notation:
const obj = { name: 'John', age: 30 };
console.log(obj.name); // Outputs: John
console.log(obj.age); // Outputs: 30
2. Bracket Notation (Dynamic Property Name)
If the property name is stored in a variable or determined dynamically, use bracket notation:
const obj = { name: 'John', age: 30 };
const propertyName = 'name';
console.log(obj[propertyName]); // Outputs: John
propertyName = 'age';
console.log(obj[propertyName]); // Outputs: 30
3. Using Variables as Property Names
If you want to create an object where the property names are determined by variables, you can do so during object creation or later:
const propertyName = 'dynamicKey';
const obj = {
[propertyName]: 'Value for dynamic key'
};
console.log(obj.dynamicKey); // Outputs: Value for dynamic key
4. Accessing Nested Object Properties
For nested objects, you can chain dot notation or use bracket notation:
const obj = {
user: {
name: 'John',
age: 30
}
};
console.log(obj.user.name); // Outputs: John
console.log(obj['user']['name']); // Outputs: John
5. Using Object.keys(), Object.values(), and Object.entries()
If you need to iterate over the properties of an object, you can use these methods:
const obj = { name: 'John', age: 30 };
// Get all property names
const keys = Object.keys(obj);
console.log(keys); // Outputs: ['name', 'age']
// Get all property values
const values = Object.values(obj);
console.log(values); // Outputs: ['John', 30]
// Get key-value pairs
const entries = Object.entries(obj);
console.log(entries); // Outputs: [['name', 'John'], ['age', 30]]
Example: Dynamic Access with a Loop
If you want to access properties dynamically based on an array of keys:
const obj = { name: 'John', age: 30, occupation: 'Developer' };
const keysToAccess = ['name', 'occupation'];
keysToAccess.forEach(key => {
console.log(`${key}: ${obj[key]}`);
});
// Outputs:
// name: John
// occupation: Developer
These methods should cover most scenarios where you need to access JavaScript object elements dynamically or with variable names.