Object Destructuring and Looping
Object destructuring is a way to quickly get values out of an object and use them in your code. It helps make your code shorter and easier to read.
Looping lets you go through all the parts of an object one by one. This is useful when you want to see or change each value inside an object.
What You’ll Learn
This page will show you how to use destructuring and loops to work with objects in a simple and clear way.
Object Destructuring
Object destructuring allows you to extract values from an object and assign them to variables in a quick and clear way.
const car = {
brand: "abc_brand",
model: "abc_model",
year: 2023
};
// Destructuring the object
const { brand, model, year } = car;
console.log(brand); // Output: abc_brand
console.log(model); // Output: abc_model
console.log(year); // Output: 2023
const car = {
brand: "abc_brand",
model: "abc_model",
year: 2023
};
// Destructuring the object
const { brand, model, year } = car;
console.log(brand); // Output: abc_brand
console.log(model); // Output: abc_model
console.log(year); // Output: 2023
What’s Happening Here:
- const { brand, model, year } = car;: This extracts the brand, model, and year properties from the car object and assigns them to new variables with the same names.
- You can now use these variables directly without having to write car.brand, car.model, etc.
- Destructuring makes your code cleaner and easier to read.
You can also assign new variable names or provide default values when destructuring, which makes it very flexible.
const { brand: carBrand, year = 2020 } = car;
console.log(carBrand); // Output: abc_brand
console.log(year); // Output: 2023 (default ignored because value exists)
const { brand: carBrand, year = 2020 } = car;
console.log(carBrand); // Output: abc_brand
console.log(year); // Output: 2023 (default ignored because value exists)
Looping Through Objects
You can loop through all the properties in an object using a for...in
loop. This helps you access or modify every key-value pair one by one.
const car = {
brand: "abc_brand",
model: "abc_model",
year: 2023
};
for (const key in car) {
console.log(key + ": " + car[key]);
}
const car = {
brand: "abc_brand",
model: "abc_model",
year: 2023
};
for (const key in car) {
console.log(key + ": " + car[key]);
}
What’s Happening Here:
- for (const key in car): This loops over each property name (key) in the car object.
- car[key]: This accesses the value of the current property.
- The console.log prints each key and its value.
Looping through objects is useful when you want to check all the data inside or perform actions on each property.
Another useful method is Object.keys()
, which gives you an array of all the keys, so you can use other loops like forEach
on them:
Object.keys(car).forEach(key => {
console.log(key + ": " + car[key]);
});
Object.keys(car).forEach(key => {
console.log(key + ": " + car[key]);
});
Example 1: Basic Object Destructuring
Let’s look at a simple object about a dog. We'll use destructuring to get values from the object and store them in variables easily.
const dog = {
name: "charlie",
breed: "Golden Retriever",
age: 5
};
// Destructure the object
const { name, breed, age } = dog;
console.log(name); // Output: charlie
console.log(breed); // Output: Golden Retriever
console.log(age); // Output: 5
const dog = {
name: "charlie",
breed: "Golden Retriever",
age: 5
};
// Destructure the object
const { name, breed, age } = dog;
console.log(name); // Output: charlie
console.log(breed); // Output: Golden Retriever
console.log(age); // Output: 5
What’s Happening Here:
- const { name, breed, age } = dog;: This extracts the values from the dog object and assigns them to variables with the same names.
- You can now use name, breed, and age without writing dog.name each time.
- This makes your code shorter and easier to read.
Output:
charlie
Golden Retriever
5
charlie
Golden Retriever
5
Destructuring is especially useful when you work with objects often, such as in functions or API responses.
Example 2: Destructuring with Default Values and Renaming
You can rename variables while destructuring, and also set default values in case a property doesn’t exist in the object.
const bird = {
type: "Parrot",
color: "Green"
};
// Destructure with renaming and default value
const { type: birdType, color, canFly = true } = bird;
console.log(birdType); // Output: Parrot
console.log(color); // Output: Green
console.log(canFly); // Output: true
const bird = {
type: "Parrot",
color: "Green"
};
// Destructure with renaming and default value
const { type: birdType, color, canFly = true } = bird;
console.log(birdType); // Output: Parrot
console.log(color); // Output: Green
console.log(canFly); // Output: true
What’s Happening Here:
- type: birdType: This renames the type property to a new variable called birdType.
- canFly = true: This sets a default value for canFly. Since it’s not in the object, the default is used.
- This way, you can avoid errors and still use expected variables.
Output:
Parrot
Green
true
Parrot
Green
true
Destructuring with renaming and default values is helpful when working with incomplete or dynamic data.
Example 3: Looping Through an Object Using forEach
You can’t use forEach
directly on an object, but you can use Object.keys()
to get an array of keys, then loop through them using forEach
.
const color = {
primary: "blue",
secondary: "green",
accent: "yellow"
};
// Loop through each key using forEach
Object.keys(color).forEach(key => {
console.log(key + ": " + color[key]);
});
const color = {
primary: "blue",
secondary: "green",
accent: "yellow"
};
// Loop through each key using forEach
Object.keys(color).forEach(key => {
console.log(key + ": " + color[key]);
});
What’s Happening Here:
- Object.keys(color) returns an array of all the keys in the color object.
- forEach goes through each key one by one.
- color[key] accesses the value for each key.
- This prints each key-value pair from the object.
Output:
primary: blue
secondary: green
accent: yellow
primary: blue
secondary: green
accent: yellow
This is a helpful way to work with objects when you want to use array methods like forEach
, map
, or filter
.
Example 4: Looping with Object.entries()
and for...of
The Object.entries()
method gives you both keys and values from an object. You can loop through them using a for...of
loop.
const train = {
name: "Express Line",
speed: "150 km/h",
capacity: 400
};
// Loop through key-value pairs
for (const [key, value] of Object.entries(train)) {
console.log(key + ": " + value);
}
const train = {
name: "Express Line",
speed: "150 km/h",
capacity: 400
};
// Loop through key-value pairs
for (const [key, value] of Object.entries(train)) {
console.log(key + ": " + value);
}
What’s Happening Here:
- Object.entries(train) gives back an array of key-value pairs from the train object.
- for...of loops through each pair.
- [key, value] pulls apart each pair so you can use the key and value directly inside the loop.
Output:
name: Express Line
speed: 150 km/h
capacity: 400
name: Express Line
speed: 150 km/h
capacity: 400
This is one of the cleanest ways to loop through both keys and values in an object.
Example 5: Looping with Object.values()
If you only care about the values (not the keys), you can use Object.values()
. It gives you an array of all the values in the object.
const airplane = {
model: "Boeing 747",
range: "13,450 km",
capacity: 416
};
// Loop through values only
Object.values(airplane).forEach(value => {
console.log(value);
});
const airplane = {
model: "Boeing 747",
range: "13,450 km",
capacity: 416
};
// Loop through values only
Object.values(airplane).forEach(value => {
console.log(value);
});
What’s Happening Here:
- Object.values(airplane) returns an array of all the values in the airplane object.
- forEach loops through each value and prints it.
- This is useful when the property names (keys) don’t matter, and you only need the data.
Output:
Boeing 747
13,450 km
416
Boeing 747
13,450 km
416
Object.values()
is simple and effective when you just want the data inside an object.
Exercises
1. Destructure the name and age from this object:
const user = {
name: "John",
age: 25,
email: "john@example.com"
};
// Your destructuring code here
const user = {
name: "John",
age: 25,
email: "john@example.com"
};
// Your destructuring code here
2. Loop through the user object and print all keys and values.
// Your loop code here
// Your loop code here
3. Use Object.entries() to loop through the object and print keys and values.
// Your code here
// Your code here
Frequently Asked Questions
What is object destructuring in JavaScript?
What is object destructuring in JavaScript?
Object destructuring is a concise syntax to pull values out of objects and assign them to variables, making code cleaner and easier to read.
How do you loop through properties of a JavaScript object?
How do you loop through properties of a JavaScript object?
You can use a for...in loop or convert the object's keys into an array with Object.keys() and loop using forEach.
Can I destructure nested objects?
Can I destructure nested objects?
Yes! You can destructure nested objects by specifying the nested keys in your destructuring pattern.
Is destructuring only for objects?
Is destructuring only for objects?
No, destructuring works for arrays and other iterable types too, allowing easy extraction of values.
Why use Object.keys() with forEach for looping?
Why use Object.keys() with forEach for looping?
Because forEach works on arrays, Object.keys() creates an array of keys from the object so you can loop through properties easily.