[英]Destructuring with nested objects and default values
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
语法错误:无效的速记属性初始值设定项
The above code will not work if the object does not have c in it如果对象中没有 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}`)
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
This example will help you to understand the destructing of array
and object
with fallback values.此示例将帮助您了解具有回退值的
array
和object
的销毁。
You can use the =
symbol for adding fallback
or default
value while destructing.您可以使用
=
符号在销毁时添加fallback
或default
值。
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 ie '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}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.