I am new to ES6 destructing. 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
.
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:
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}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.