Destructuring array and object from a nested object
Destructuring Array and Object from a Nested Object
Have you ever come across a situation where you had to extract values from a nested object and use them in your code? One way to achieve this is by using destructuring.
Let's say we have a nested object like this:
const person = {
name: "John Doe",
age: 30,
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zip: "12345"
},
hobbies: ["reading", "swimming", "traveling"]
};
To extract values from this object, we need to use destructuring. Here's how we can do it:
Extracting Values from Object
const {name, age, address, hobbies} = person;
console.log(name); // "John Doe"
console.log(age); // 30
console.log(address); // { street: "123 Main St", city: "Anytown", state: "CA", zip: "12345" }
console.log(hobbies); // ["reading", "swimming", "traveling"]
Using the curly braces, we can extract the values of name, age, address, and hobbies from the person object. The extracted values are assigned to variables with the same name as the object property.
Now let's extract values from the nested address object:
const {street, city, state, zip} = address;
console.log(street); // "123 Main St"
console.log(city); // "Anytown"
console.log(state); // "CA"
console.log(zip); // "12345"
We can also extract values from the hobbies array:
const [hobby1, hobby2, hobby3] = hobbies;
console.log(hobby1); // "reading"
console.log(hobby2); // "swimming"
console.log(hobby3); // "traveling"
Using square brackets, we can extract the values of the hobbies array and assign them to variables hobby1, hobby2, and hobby3.
Extracting Values from Array of Objects
Let's say we have an array of objects like this:
const people = [
{name: "John", age: 30},
{name: "Jane", age: 25},
{name: "Jim", age: 35}
];
To extract values from this array of objects, we can use destructuring like this:
const [{name: name1, age: age1}, {name: name2, age: age2}, {name: name3, age: age3}] = people;
console.log(name1); // "John"
console.log(age1); // 30
console.log(name2); // "Jane"
console.log(age2); // 25
console.log(name3); // "Jim"
console.log(age3); // 35
Using curly braces and square brackets, we can extract the values of name and age properties from each object in the array and assign them to variables with different names.