js object destructuring

When object destructuring (Object Destructuring), there are several important concepts to understand:

  1. Basic object deconstruction:
    • Use curly braces ( {}) to define destructuring patterns.
    • Destructuring mode assigns the attribute values ​​in the object to the corresponding variables based on the attribute names.
    • Destructuring is based on the matching of attribute names, and the order of variables has nothing to do with the order of attributes in the object.
const person = {
    
     name: 'Alice', age: 25 };

const {
    
     name, age } = person;

console.log(name); // 输出:Alice
console.log(age); // 输出:25
  1. Defaults:
    • Default values ​​can be specified for destructured variables to prevent the corresponding value from being destructured undefined.
const person = {
    
     name: 'Alice', age: 25 };

const {
    
     name, age, occupation = 'Unknown' } = person;

console.log(name); // 输出:Alice
console.log(age); // 输出:25
console.log(occupation); // 输出:Unknown
  1. Alias:
    • Alias ​​can be used to give destructured variables different names.
const person = {
    
     name: 'Alice', age: 25 };

const {
    
     name: fullName, age: years } = person;

console.log(fullName); // 输出:Alice
console.log(years); // 输出:25
  1. Multi-level object destructuring:
    • You can use the nested destructuring pattern to deconstruct multi-level nested objects.
const person = {
    
    
  name: 'Alice',
  age: 25,
  address: {
    
    
    city: 'New York',
    country: 'USA'
  }
};

const {
    
     name, address: {
    
     city, country } } = person;

console.log(name); // 输出:Alice
console.log(city); // 输出:New York
console.log(country); // 输出:USA
  1. Object array destructuring
    • Combine the syntax of arrays and objects in destructuring mode to extract object attribute values ​​​​from arrays
    • The property names and variable names in the destructuring pattern need to match the property names of the object, and the array index needs to correspond to the position of the object to be destructured in the array.
const data = [
  {
    
     name: 'Alice', age: 25 },
  {
    
     name: 'Bob', age: 30 },
  {
    
     name: 'Charlie', age: 35 }
];

const [{
    
     name: firstPersonName, age: firstPersonAge }, , {
    
     name: thirdPersonName, age: thirdPersonAge }] = data;

console.log(firstPersonName); // 输出:Alice
console.log(firstPersonAge); // 输出:25
console.log(thirdPersonName); // 输出:Charlie
console.log(thirdPersonAge); // 输出:35

Guess you like

Origin blog.csdn.net/qq_41045651/article/details/131597776