Javascript Array/Object Destructuring - With Some Tricks You Probably Dont Know
Syakir
Posted on July 10, 2024
This post is originally posted at https://devaradise.com/js-array-object-destructuring/
Discover some tips and tricks to destructure array and object in javascript from basic to advanced use case that you probably don't know.
Destructuring is a powerful feature in JavaScript that allows you to extract values from an array or object properties into distinct variables. It provides a more readable and concise syntax for handling data structures, making your code cleaner and more maintainable.
In this article, we’ll explore the basics of array and object destructuring, along with some advanced use cases.
Array Destructuring
Array destructuring allows you to unpack values from arrays into separate variables. This can simplify the process of working with arrays and make your code more readable.
Basic Array Destructuring
Here’s a simple example of array destructuring:
const fruits = ['apple', 'banana', 'cherry'];
const [first, second, third] = fruits;
console.log(first); // Outputs: apple
console.log(second); // Outputs: banana
console.log(third); // Outputs: cherry
Skipping Items
You can skip items in an array by using commas:
const colors = ['red', 'green', 'blue', 'yellow'];
const [primary, , secondary] = colors;
console.log(primary); // Outputs: red
console.log(secondary); // Outputs: blue
Assigning Default Value
You can assign a default value to an index, in a case when you dont know if the array have enough length. For example, when you receive the array from a backend API
const numbers = [1, 2];
const [a, b, c = 3] = numbers;
console.log(a); // Outputs: 1
console.log(b); // Outputs: 2
console.log(c); // Outputs: 3 (default value)
Swapping Variables
Array destructuring makes it easy to swap variables without using a temporary variable:
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x); // Outputs: 2
console.log(y); // Outputs: 1
Destructure some items only + Rest operator
const [first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(first); // Outputs: 10
console.log(second); // Outputs: 20
console.log(rest); // Outputs: [30, 40, 50]
Object Destructuring
Object destructuring allows you to extract properties from objects into distinct variables. It provides a concise way to access object properties.
Basic Object Destructuring
Here’s a basic example of object destructuring:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const { name, age, city } = person;
console.log(name); // Outputs: John
console.log(age); // Outputs: 30
console.log(city); // Outputs: New York
Renaming Variables
You can rename variables while destructuring by using a colon:
const user = {
username: 'jdoe',
email: 'jdoe@example.com'
};
const { username: userName, email: userEmail } = user;
console.log(userName); // Outputs: jdoe
console.log(userEmail); // Outputs: jdoe@example.com
Assigning Default Value
Like Array destructuring, you can also assign the default value of property in case the object doesn’t have the specified property
const options = {
timeout: 1000
};
const { timeout, retries = 3 } = options;
console.log(timeout); // Outputs: 1000
console.log(retries); // Outputs: 3 (default value)
Nested Destructuring
You can destructure nested objects and arrays easily:
const employee = {
name: 'Alice',
position: {
title: 'Developer',
level: 'Junior'
},
skills: ['JavaScript', 'React']
};
const {
name,
position: { title, level },
skills: [primarySkill, secondarySkill]
} = employee;
console.log(name); // Outputs: Alice
console.log(title); // Outputs: Developer
console.log(level); // Outputs: Junior
console.log(primarySkill); // Outputs: JavaScript
console.log(secondarySkill); // Outputs: React
Combining Array and Object Destructuring
You can combine array and object destructuring to handle complex data structures:
const data = {
users: [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]
};
const {
users: [{ name: firstName }, { name: secondName }]
} = data;
console.log(firstName); // Outputs: John
console.log(secondName); // Outputs: Jane
Function Parameters Destructuring
Destructure arrays and objects directly in function parameters:
Array Destructuring in Function Parameters
function sum([a, b]) {
return a + b;
}
console.log(sum([1, 2])); // Outputs: 3
Object Destructuring in Function Parameters
function greet({ name, age }) {
return `Hello, my name is ${name} and I am ${age} years old.`;
}
const person = { name: 'John', age: 30 };
console.log(greet(person)); // Outputs: Hello, my name is John and I am 30 years old.
Destructuring with Promises
Handle asynchronous data with destructuring:
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
user: {
id: 1,
name: 'John Doe'
},
posts: [
{ id: 1, title: 'Post 1' },
{ id: 2, title: 'Post 2' }
]
});
}, 1000);
});
};
fetchData().then(({ user, posts }) => {
console.log(user.name); // Outputs: John Doe
console.log(posts[0].title); // Outputs: Post 1
});
Conclusion
Array and object destructuring in JavaScript provides a concise and readable way to extract values from arrays and objects. By leveraging destructuring, you can simplify your code, making it more maintainable and easier to understand. Whether you’re dealing with simple arrays and objects or complex nested structures, destructuring offers a powerful tool for efficient data handling in JavaScript.
Do you know another trick for array/object destructuring?
Dont hesitate to share it in the comment below!
Posted on July 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.