Object destructuring in Javascript
In JavaScript, object destructuring is a feature that allows you to extract values from an object and assign them to variables. It is often used in combination with array destructuring, which allows you to extract values from arrays and assign them to variables.
Here's an example of object destructuring in JavaScript:
const person = {
name: 'John',
age: 30,
address: {
city: 'New York',
state: 'NY'
}
};
const { name, age } = person;
console.log(name); // Output: 'John'
console.log(age); // Output: 30
In this example, the name
and age
properties of the person
the object is extracted and assigned to the name
and age
variables, respectively.
Object destructuring can also be used to extract nested properties and to assign default values to variables if the property does not exist in the object. Here's an example:
const person = {
name: 'John',
age: 30
};
const { name, age, address = { city: 'Unknown', state: '??' } } = person;
console.log(name); // Output: 'John'
console.log(age); // Output: 30
console.log(address); // Output: { city: 'Unknown', state: '??' }
In this example, the address
property is not defined in the person
object, so the default value is used instead.
Object destructuring is a useful feature in JavaScript that can make it easier to work with complex data structures and can make your code more concise and easier to read. It is particularly useful when working with API responses and other data that may have a complex structure.