Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6/Next: object destructuring with rest - grouping

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:

  • gallery = []
  • select = () => null
  • other = {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:

  • specific = {gallery: [], select: () => null}
  • other = {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.

like image 822
Kocur4d Avatar asked Nov 03 '16 10:11

Kocur4d


1 Answers

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.

like image 155
César Landesa Avatar answered Sep 21 '22 17:09

César Landesa