I have:
const props = {
gallery: [],
select: () => null,
one: 1,
two: 2,
}
I can destructure it with:
const {gallery, select, ...other} = props
I will have three variables now:
[]
() => null
{one: 1,two: 2}
Is it possible to destucture to a specify grouping?
Something like this(this is not going to work but I hope it is clear to see what I am trying to do):
const {{gallery, select}: specific, ...other} = props
So I will have 2 variables:
{gallery: [], select: () => null}
{one: 1,two: 2}
I could solve it at the higher level and build the props in this way:
const props = {
specific: {
gallery: [],
select: () => null,
},
other: {
one: 1,
two: 2,
}
}
But I am just wondering if this is possible with destructuring.
What about this? others
contains also the specific
data and I must access first to the props
(maybe this could be improved), but I think that it basically groups while destructuring. It works because you can assign a default value when the attribute does not exist:
const props = {
gallery: [],
select: () => null,
one: 1,
two: 2,
}
const {gallery : gal, select : sel} = props;
const {specific: specific={gallery: gal, select: sel}, ...others} = props;
console.log(specific);
console.log(others);
EDIT
You can also change
const {gallery : gal, select : sel} = props;
const {specific: specific={gallery: gal, select: sel}, ...others} = props;
with:
const {specific: specific={gallery: props.gallery, select: props.select}, ...others} = props;
if you want it in one line.
Also, maioman's answer solves the problem I mentioned with others
containing the specific
data and doesn't directly access props.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With