Data Structures: Objects
Explore how to define and work with JavaScript objects, including creating properties, accessing values using dot and bracket notation, and iterating over properties with loops. This lesson helps you understand objects as versatile data structures to store and organize information effectively.
We'll cover the following...
Introduction to objects
A JavaScript object is another variable that allows us to store multiple pieces of data. Like arrays, objects are capable of storing any valid JavaScript data type, including arrays and other objects. However, unlike arrays, data in objects are stored in object properties.
Let’s once again take the example of a classroom with students. We will make a single student an object with multiple properties:
An object is declared using curly braces ({}). Properties and their values are stored within the curly braces, separated by a colon (:). Each property is separated by a comma (,), which comes after each property’s value.
The following object has two properties: name and age. You can access the student object’s property values by looking up a property using either dot notation or bracket notation:
As previously stated, an object’s property values can be any valid JavaScript data type. Here’s a student object with a grades property with a value that is another object:
Once an object has been created, you can add additional properties by using dot or bracket notation:
You can also remove a property from an object using the delete keyword:
Test your understanding
How would you access the quiz1 grade in the student object shown below?
var student = {
name: "Mary",
age: 10,
grades: {
quiz1: 90,
quiz2: 88,
quiz3: 95
}
}
student["grades"]["quiz1"];
student.grades.quiz1;
student.grades["quiz1"];
student["grades"].quiz1;
All of the above
Exercise #
Convert the following array of arrays:
[ ["Mary", 10], ["Barbara", 11], ["David", 12], ["Alex", 11] ];
into an array of objects, named students. Each object in the array should have a name and age property.
Iterating through object properties
Like with arrays, we can use a loop to go through all an object’s properties to access its values.
JavaScript provides a special for...in syntax for iterating through object properties. Let’s take a look at another student object and go through its properties:
Notice how this loop logs the object’s properties to the console. To access the value associated with each property, you must use bracket notation, like this:
Exercise
Given an array of student objects, structured like so:
var students = [
{
name: "Mary",
age: 10,
grades: [90, 88, 95]
},
{
name: "Joseph",
age: 11,
grades: [80, 100, 90, 96]
}
];
Write a function that returns an array of grade averages. For instance, if the returned array was named averages:
averages[0]would equal91averages[1]would equal91.5
Assume each student object in your array has a grades property.