Language: EN

javascript-destructuracion-objetos

Destructuring Collections in JavaScript

The destructuring of objects is a feature of JavaScript that allows you to extract properties from an object and assign them to variables individually.

With destructuring, we can quickly access the properties of an object without the need to use 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 obtain 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 name of the variable.

The basic syntax is as follows:

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

const { property1, property2 } = object;

In this example, the variables property1 and property2 are assigned to the corresponding properties of the 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

Custom Names

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

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

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

Default Values

We can also assign default values to 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

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

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

Usage in Functions

Destructuring can also be applied directly to function parameters.

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

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

printProperties(object);

In this example,

  • The object object is passed to the function printProperties
  • There, the properties property1 and property2 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

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

Practical Examples