Javascript Objects (key-value pairs, accessing properties, nested objects)
JavaScript objects are a fundamental data structure consisting of key-value pairs.
1. Creating JavaScript Objects
An object can be created using curly braces {}
with keys (properties) and values:
const person = {name: "Amir",age: 30,isDeveloper: true};
2. Accessing Properties
You can access properties in two ways:
Dot Notation:
object.property
Bracket Notation:
object["property"]
console.log(person.name); // Output: "Amir"console.log(person["age"]); // Output: 30
3. Adding and Modifying Properties
You can add or modify properties using dot or bracket notation.
person.city = "Tehran";person["country"] = "Iran";console.log(person);// { name: 'Amir', age: 30, isDeveloper: true, city: 'Tehran', country: 'Iran' }
4. Deleting Properties
Use the delete
keyword to remove properties.
delete person.isDeveloper;console.log(person);// { name: 'Amir', age: 30, city: 'Tehran', country: 'Iran' }
5. Nested Objects
Objects can contain other objects as values, creating a nested structure.
const user = {id: 1,name: "Amir",address: {street: "123 Main St",city: "Tehran",country: "Iran"}};
Accessing Nested Properties
To access nested properties, chain the dot or bracket notation.
console.log(user.address.city); // Output: "Tehran"console.log(user["address"]["country"]); // Output: "Iran"
Modifying Nested Properties
You can also modify nested properties similarly.
user.address.street = "456 Elm St";console.log(user.address.street); // Output: "456 Elm St"
Optional Chaining
For deeply nested properties, optional chaining (?.
) is helpful if some properties might be undefined
.
console.log(user.address?.zipCode); // Output: undefined, without error
6. Looping Through Properties
To loop through an object’s properties, use for...in
or Object.keys()
.
for (let key in user) {console.log(key, user[key]);}
Or using Object.entries()
for both keys and values:
Object.entries(user).forEach(([key, value]) => {console.log(key, value);});
7. Checking Property Existence
Use the in
operator or hasOwnProperty()
.
console.log("name" in person); // trueconsole.log(person.hasOwnProperty("age")); // true
Mastering these techniques allows for more complex manipulations, especially useful in frameworks like React and data-driven applications.