Week 7: Structuring Data with Objects

Learn to represent complex data using key-value pairs in JavaScript Objects.

Explore Chapter 7

Chapter 7: Structuring Data with Key-Value Pairs

Introduction to Objects: Key-Value Collections.

Objects are a fundamental data type in JavaScript, used to store collections of related data and functionality. Unlike arrays which use numerical indices, objects use named keys (also called properties) to access their associated values. This makes them ideal for representing real-world entities or structured data, similar to dictionaries in Python.

Creating Objects (Object Literals)

The most common way to create an object is using object literal syntax {}.

// Empty object
let emptyObject = {};

// Object representing a user
let user = {
  firstName: "Alice", // key: value (firstName is the key, "Alice" is the value)
  lastName: "Smith",
  age: 30,           // Keys are usually strings (quotes often optional if valid identifier)
  isActive: true,
  "zip code": "10001" // Keys with spaces or special chars need quotes
};

// Object representing a car
let car = {
  make: "Toyota",
  model: "Camry",
  year: 2022,
  features: ["GPS", "Sunroof", "Bluetooth"] // Values can be any type, including arrays
};
  • Keys are typically strings (or Symbols). If a key is a valid JavaScript identifier, quotes are usually optional.
  • Values can be any valid JavaScript data type: strings, numbers, booleans, arrays, other objects, functions, etc.
  • Key-value pairs are separated by commas.
  • Objects are collections of properties, and the order of properties is generally not guaranteed (though modern JS engines often preserve insertion order).

Objects allow you to group related data under meaningful names, making your code more organized and readable.

Accessing and Modifying Object Properties.

You can access and change the values associated with an object's keys (properties).

Accessing Properties

There are two main ways to access object properties:

  • Dot Notation (.): Used when the key is a valid JavaScript identifier (no spaces, doesn't start with a number, etc.). This is the most common method.
    let person = { name: "Bob", city: "London" };
    
    console.log(person.name); // Output: Bob
    console.log(person.city); // Output: London
  • Bracket Notation ([]): Used when the key is stored in a variable, contains special characters, or is not a valid identifier. The key inside the brackets must be a string (or evaluate to a string).
    console.log(person["name"]); // Output: Bob
    
    let propertyName = "city";
    console.log(person[propertyName]); // Output: London (Accessing via variable)
    
    let book = { "title-with-hyphens": "Great Expectations" };
    console.log(book["title-with-hyphens"]); // Bracket notation needed here
    

If you try to access a property that doesn't exist, you will get undefined (unlike Python dictionaries which raise a KeyError).

console.log(person.country); // Output: undefined

Modifying Properties

Objects are mutable. You can change the value of an existing property or add a new property using assignment (=):

let student = { id: 101, major: "Computer Science" };

// Modify existing property
student.major = "Data Science";
console.log(student.major); // Output: Data Science

// Add a new property
student.gpa = 3.8;
student["enrollmentStatus"] = "Active"; // Using bracket notation

console.log(student); // { id: 101, major: 'Data Science', gpa: 3.8, enrollmentStatus: 'Active' }

Deleting Properties

You can remove a property from an object using the delete operator:

delete student.gpa;
console.log(student); // { id: 101, major: 'Data Science', enrollmentStatus: 'Active' }
console.log(student.gpa); // Output: undefined

Object Methods: Functions as Properties.

When a function is stored as a property of an object, it's called a method. Methods define the actions or behaviors that an object can perform. They often operate on the data contained within the object itself.

Defining Methods

You define a method like any other property, but assign a function as the value.

let calculator = {
  value: 0,
  add: function(num) { // Traditional function expression
    this.value += num; // 'this' refers to the calculator object itself
  },
  subtract(num) { // Shorthand method syntax (ES6+)
    this.value -= num;
  },
  getValue() { // Shorthand syntax
    return this.value;
  }
};

Calling Methods

You call methods using dot notation, followed by parentheses () to invoke the function.

console.log(calculator.getValue()); // Output: 0

calculator.add(10);
console.log(calculator.getValue()); // Output: 10

calculator.subtract(3);
console.log(calculator.getValue()); // Output: 7

The this Keyword

Inside an object method defined using traditional syntax or shorthand, the keyword this typically refers to the object the method was called on (e.g., calculator in the example above). This allows methods to access and manipulate the object's own properties (this.value). Arrow functions handle this differently, which we'll discuss later.

Iterating Over Object Properties.

Sometimes you need to loop through the properties of an object.

for...in Loop

The for...in loop iterates over the enumerable property keys (names) of an object.

let course = {
  title: "JavaScript Basics",
  duration: "12 Weeks",
  level: "Beginner"
};

console.log("Course Properties:");
for (let key in course) {
  // 'key' will be "title", then "duration", then "level"
  // Check if the property belongs to the object itself (not inherited)
  if (course.hasOwnProperty(key)) {
      console.log(`${key}: ${course[key]}`); // Use bracket notation to get value
  }
}

Output:

Course Properties:
title: JavaScript Basics
duration: 12 Weeks
level: Beginner

Note: It's often recommended to include the hasOwnProperty() check inside a for...in loop to ensure you are only iterating over the object's own properties, not properties inherited from its prototype chain (a more advanced concept).

Other Iteration Methods (Object.keys, Object.values, Object.entries)

Modern JavaScript provides methods to get arrays of keys, values, or key-value pairs, which you can then iterate over using array methods like forEach:

let car = { make: "Honda", model: "Civic", year: 2021 };

// Get an array of keys
let keys = Object.keys(car); // ["make", "model", "year"]
console.log("Keys:", keys);
keys.forEach(key => console.log(`Key: ${key}`));

// Get an array of values
let values = Object.values(car); // ["Honda", "Civic", 2021]
console.log("Values:", values);
values.forEach(value => console.log(`Value: ${value}`));

// Get an array of [key, value] pairs
let entries = Object.entries(car); // [ ["make", "Honda"], ["model", "Civic"], ["year", 2021] ]
console.log("Entries:", entries);
entries.forEach(([key, value]) => { // Using array destructuring
  console.log(`${key} -> ${value}`);
});

These methods (Object.keys, Object.values, Object.entries) are often preferred over for...in in modern code because they don't iterate over inherited properties and work well with standard array iteration techniques.

Syllabus