J

Desestructuración

JavaScript syntax guide

Extraer valores de arrays y objetos

Desestructuración

Extraer valores de arrays y objetos

JavaScript desestructuración (javascript)
        
          // 1. ARRAY DESTRUCTURING
const numbers = [10, 20, 30, 40, 50];

// Basic destructuring
const [first, second] = numbers;
console.log(first, second); // 10, 20

// Skip elements
const [, , third] = numbers;
console.log(third); // 30

// Rest operator for remaining elements
const [head, ...tail] = numbers;
console.log(head, tail); // 10, [20, 30, 40, 50]

// Default values
const [a = 1, b = 2, c = 3] = [100];
console.log(a, b, c); // 100, 2, 3

// Swapping variables (no temporary variable needed!)
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2, 1

// 2. OBJECT DESTRUCTURING
const user = {
  name: 'Alice',
  age: 28,
  job: 'Designer',
  location: {
    city: 'New York',
    country: 'USA'
  },
  hobbies: ['reading', 'coding', 'gaming']
};

// Basic destructuring
const { name, age } = user;
console.log(name, age); // Alice, 28

// Renaming variables
const { name: userName, job: profession } = user;
console.log(userName, profession); // Alice, Designer

// Default values
const { salary = 50000, department = 'General' } = user;
console.log(salary, department); // 50000, General

// Nested destructuring
const { location: { city, country } } = user;
console.log(city, country); // New York, USA

// 3. ADVANCED PATTERNS
// Destructuring function parameters
function createUser({ name, age, email, ...otherProps }) {
  return {
    id: Date.now(),
    name: name || 'Anonymous',
    age: age || 18,
    email: email || 'no-email@example.com',
    ...otherProps
  };
}

const newUser = createUser({
  name: 'Bob',
  age: 25,
  email: 'bob@example.com',
  department: 'Engineering'
});
console.log(newUser);

// Destructuring in loops
const users = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob', role: 'user' },
  { id: 3, name: 'Charlie', role: 'moderator' }
];

for (const { id, name, role } of users) {
  console.log(`${name} (${id}) is a ${role}`);
}

// 4. PRACTICAL EXAMPLES
// API Response handling
function processApiResponse(response) {
  const {
    data: {
      user: { name, email },
      posts = []
    },
    status,
    message
  } = response;

  if (status !== 'success') {
    throw new Error(message);
  }

  return { user: { name, email }, posts };
}

// React component props (concept)
function UserCard({ user: { name, avatar }, onClick, className = '' }) {
  return `<div class="${className}" onclick="${onClick}">
    <img src="${avatar}" alt="${name}'s avatar">
    <h3>${name}</h3>
  </div>`;
}

// Configuration object
const config = {
  server: { host: 'localhost', port: 3000 },
  database: { url: 'mongodb://localhost:27017' },
  features: { auth: true, logging: false }
};

const {
  server: { host, port },
  database: { url: dbUrl },
  features: { auth: isAuthEnabled, logging: isLoggingEnabled }
} = config;

console.log(`Server: ${host}:${port}`);
console.log(`Database: ${dbUrl}`);
console.log(`Auth enabled: ${isAuthEnabled}`);

// 5. DESTRUCTURING WITH REGEX MATCHES
const url = 'https://www.example.com/path?param=value';
const regex = /^https?:\/\/([^/?#]+)([^?#]*)/;
const [, domain, path] = url.match(regex) || [];
console.log(domain, path); // www.example.com, /path

// 6. MIXED DESTRUCTURING
const mixedData = {
  items: [
    { id: 1, title: 'First' },
    { id: 2, title: 'Second' }
  ],
  metadata: {
    total: 2,
    page: 1
  }
};

const {
  items: [firstItem, secondItem],
  metadata: { total, page }
} = mixedData;

console.log(firstItem.title, total); // First, 2

// 7. DESTRUCTURING IN RETURN STATEMENTS
function getCoordinates() {
  return { x: 10, y: 20, z: 30 };
}

const { x, y } = getCoordinates();
console.log(x, y); // 10, 20

// 8. COMPUTED PROPERTY NAMES (Advanced)
const dynamicKey = 'theme';
const settings = {
  [dynamicKey]: 'dark',
  language: 'en',
  notifications: true
};

const { [dynamicKey]: selectedTheme, ...otherSettings } = settings;
console.log(selectedTheme, otherSettings); // dark, { language: 'en', notifications: true }
        
      

Explanation

La desestructuración permite extraer valores de arrays y objetos en variables. Proporciona una forma concisa de acceder a estructuras de datos anidadas.

Common Use Cases

  • Extraer datos de respuesta de API
  • Parámetros de función
  • Objetos de configuración
  • Gestión de estado

Related JavaScript Syntax

Master Desestructuración in JavaScript

Understanding desestructuración is fundamental to writing clean and efficient JavaScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using desestructuración effectively in your JavaScript projects.

Key Takeaways

  • Extraer datos de respuesta de API
  • Parámetros de función
  • Objetos de configuración