Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add default value and alias using ES6 de-structuring?

I have a specific use case where I want to do a nested de-structuring and assign an alias (rename it to another variable name, say aliasD) as well as a default value to a property. E.g.

const a = { b: { c: [{ d: 'value' }] } };

and while destructuring I only need d but with an alias aliasD and a default value defaultVal. SO I tried below, but I am not sure what I am missing

const a = { b: { c: [{ d: 'value' }] } };
const { b: { c: [first: { d: aliasD = defaultVal }] } } = a;

console.log(aliasD);

But this doesn't work

like image 528
Aditya Singh Avatar asked Oct 23 '25 08:10

Aditya Singh


1 Answers

The problem here is for destructuring the array, the correct syntax to get the first value of the array would be:

[varName] = yourArray

Applying that to your example:

const { b: { c: [{ d: aliasD = 'test' }] } } = a;

You can try it out with Babel REPL

like image 166
Lucas Avatar answered Oct 24 '25 21:10

Lucas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!