Object Destructuring
May 1, 2021
Destructuring is used whenever we need to basically get some data out of an object or out of an array. In other words, is a short, clean syntax for unpacking values from arrays and properties from objects into distinct variables.
It is important to note from the beginning that in object destructuring, the value assigned to the variables does not depend on the order; it is based on the property names.
Simple destructuring looks as follows:
const user = {
id: 101,
firstName: "Bob",
lastName: "Gilde",
age: 36,
};
const { id, firstName, lastName, age } = user;
console.log(id, firstName, lastName, age); // 101 "Bob" "Gilde" 36
You can assign to new variables with different names than the object properties:
const { id: userId, firstName: userFirstName } = user;
console.log(id); // Uncaught ReferenceError: id is not defined
console.log(userId); // 101
You can assign the rest of an object to a variable:
const numbers = {
a: 10,
b: 20,
c: 30,
d: 40,
};
const { a, ...rest } = numbers;
console.log(a); // 10
console.log(rest); // {b: 20, c: 30, d: 40}
If an object contains nested objects, we can use a more complex pattern to extract values.
const nums = { a: { b: { c: 10, d: 20, e: { f: 30 } } } };
const {
a,
a: {
b: { c, d, e },
},
} = nums;
console.log(a); // {b: {c: 10, d: 20, e: {f: 30}}}
console.log(c); // 10
console.log(d); // 20
console.log(e); // {f: 30}