[英]ES6 Destructing for objects
I am new to ES6 destructing. 我不熟悉ES6。 I have an object which contains another object.
我有一个包含另一个对象的对象。 I want to store certain values from the nested object.
我想存储嵌套对象中的某些值。
For example - 例如 -
z = {g: 1, h: 2, i: {d1:5, d2:6, d3:7}}
When I do 当我做
let { g, i : {d1, d3}, ...less } = z
the less
variable only stores h
and not d2
. less
变量仅存储h
而不存储d2
。
Is there a way to make it so it is 有没有办法做到这一点
less = {h, i : {d2}}
No there is not. 不,那里没有。 What you could do is
你能做的是
let { g, i: { d1, d3, ...less2 }, ...less } = z
let less = { ...less, i: less2 };
This extracts the remainder and merges them back together while preserving the shape. 这将提取其余部分,然后将它们合并在一起,同时保留形状。
No, unfortunately this is not possible. 不,很遗憾,这是不可能的。
You can however extract the missing values from i with a second rest spread: 但是,您可以通过第二次剩余价差从i中提取缺失值:
let z = {g: 1, h: 2, i: {d1:5, d2:6, d3:7}}; let { g, i : {d1, d3, ...i_less}, ...rest_less } = z; let less = { i: i_less, ...rest_less }; console.log(less)
This is my way, hope it could help. 这是我的方式,希望对您有所帮助。
let z = { g: 1, h: 2, i: { d1:5, d2:6, d3:7 } } let {g, i: {d1, d3, ...less1}, ...less2} = z let less = { i: less1, ...less2, } console.log(less); // output: {h: 2, i:{d2:6}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.