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);
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
Share Improve this question edited Feb 21, 2017 at 18:00 Aditya Singh asked Feb 21, 2017 at 17:33 Aditya SinghAditya Singh 16.7k15 gold badges48 silver badges69 bronze badges 10- Can you show what you start with and what you want to end up with? That is not clear to me. – jfriend00 Commented Feb 21, 2017 at 17:39
-
Why is there
first
there? – Andrew Li Commented Feb 21, 2017 at 17:40 - @jfriend00 Doesn't the first line of the question clarify that I want to destructure with an alias and also a default value? Not sure what else you looking for? – Aditya Singh Commented Feb 21, 2017 at 17:42
- @AndrewLi I was trying to alias first item of array. But guess that's not needed. – Aditya Singh Commented Feb 21, 2017 at 17:42
- 1 @AdityaSingh no it's not... – Andrew Li Commented Feb 21, 2017 at 17:44
1 Answer
Reset to default 6The 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