Destructuring with nested objects and default values

会有一股神秘感。 提交于 2020-11-26 11:56:38

问题


I'm using destructuring to declare some variables like this:

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

Is there a way to make this into single line? I've tried something like :

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

But it gives me an error:

SyntaxError: Invalid shorthand property initializer


回答1:


Just replace = with ::

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

Demo:

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}`)

It prints:

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



回答2:


The above code will not work if the object does not have c in it

const { a, b, c: { e = 'default', f = 'default'}} = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
This will print out an error. For completion, you could as a simple "={}" as default

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



回答3:


This example will help you to understand the destructing of array and object with fallback values.

You can use the = symbol for adding fallback or default value while destructing.

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}`);


来源:https://stackoverflow.com/questions/39049399/destructuring-with-nested-objects-and-default-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!