admin管理员组文章数量:1414605
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
本文标签: javascriptHow to add default value and alias using ES6 destructuringStack Overflow
版权声明:本文标题:javascript - How to add default value and alias using ES6 de-structuring? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745193444a2647023.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论