javascript-destructuracion-objetos

Destructuring Collections in JavaScript

  • 4 min

Destructuring of objects is a feature in JavaScript that allows extracting properties from an object and assigning them to individual variables.

With destructuring, we can quickly access an object’s properties without needing multiple lines of code (which greatly simplifies the code).

It is very useful when working with complex data, such as nested objects, or those we get as responses from APIs.

Basic Syntax

Object destructuring uses curly braces ({}) to extract properties from the object and assign them to variables. The key of each property must match the variable name.

The basic syntax is as follows:

const object = {
  property1: 'value1',
  property2: 'value2'
};

const { property1, property2 } = object;
Copied!

In this example, the variables property1 and property2 are assigned to the corresponding properties of the object object.

Let’s see it with an example

const product = { name: "Computer", price: 1000 };
const { name, price } = product;

console.log(name); // "Computer"
console.log(price); // 1000
Copied!

Custom Names

If you need to use a variable name different from the property name, you can rename them at the moment of destructuring.

const product = { name: "Computer", price: 1000 };
const { name: productName, price: cost } = product;

console.log(productName); // "Computer"
console.log(cost); // 1000
Copied!

Default Values

We can also assign default values to the values. If the property does not exist in the object, the default value will be used.

const product = { name: "Computer" };
const { name, price = 500 } = product;

console.log(name); // "Computer"
console.log(price); // 500
Copied!

In this example, since the price property does not exist in the object, the default value 500 is assigned to the price variable.

Nested Objects

When properties are nested within objects, you can destructure them hierarchically.

const user = {
  id: 1,
  profile: { name: "Ana", age: 30 },
};

const {
  profile: { name, age },
} = user;

console.log(name); // "Ana"
console.log(age); // 30
Copied!

Use in Functions

Destructuring can also be applied directly in function parameters.

function printProperties({ property1, property2 }) {
  console.log(property1);
  console.log(property2);
}

const object = {
  property1: 'value1',
  property2: 'value2'
};

printProperties(object);
Copied!

In this example,

  • The object object is passed to the printProperties function
  • There, the property1 and property2 properties of the object are destructured and printed.

They can also be used in the objects returned by a function.

function getData() {
  return { name: "Mario", age: 33 };
}

const { name, age } = getData();

console.log(name); // "Mario"
console.log(age);   // 33
Copied!

This example shows how to directly destructure the value returned by a function into name and age.

Practical Examples