使用嵌套对象和默认值进行解构

Destructuring with nested objects and default values

我正在使用解构来声明一些这样的变量:

const { a, b, c } = require('./something'),
    { e = 'default', f = 'default'} = c;

有没有办法把它变成单行? 我试过类似的东西:

const { a, b, c = { e = 'default', f = 'default'} } = require('./something');

但是它给我一个错误:

SyntaxError: Invalid shorthand property initializer

只需将 = 替换为 ::

const {a, b, c: {e = 'default', f = 'default'}} = require('./something')

演示:

const { a, b, c: { e = 'default', f = 'default'} } = {a: 1, b: 2, c: {e: 3}}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)

它打印:

a: 1, b: 2, e: 3, f: default

如果对象中没有 c,上述代码将无法运行

const { a, b, c: { e = 'default', f = 'default'}} = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
这将打印出一个错误。 为了完成,您可以将简单的“={}”作为默认值

const { a, b, c: { e = 'default', f = 'default'} ={} } = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)

此示例将帮助您了解 arrayobjectfallback 值的析构。

您可以使用 = 符号在析构时添加 fallbackdefault 值。

const person = {
  firstName: 'Nikhil',
  address: {
    city: 'Dhule',
    state: 'MH'
  },
  /*children: [
    { 
      name: 'Ninu',
      age: 3
    } 
  ]*/
}

const { 
  firstName, 
  address: {
    city,
    state
  },
  children: { 
    0: { 
      name='Oshin' // Fallback for name is string i.e 'Oshin'
    }={} // Fallback for 1st index value of array is blank object
  }=[] // Fallback for children is blank array
} = person;
  
console.log(`${firstName} is from ${city} and his first child name is ${name}`);