0

Don't know if is possible with ES6. I'm working in a project that have a function which is passed an Object with lots of properties. Right now the code is as follows:

function foo({arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8}){
   this.model = arg1;
   this.model = arg2;
   // and so on...
};
obj = {
    arg1: 'some',
    arg2: 'whatever',
    arg3: 'text'
    // and so on up to 8
    arg8: 'end text'
    }
foo(obj);

Mi DESIRED output would be,if possible, accessing the parameters like this:

function foo( {...args} ){ // not working
   this.model = arg1;
   this.model = arg2;
   // and so on...
};

obj = {
    arg1: 'some',
    arg2: 'whatever',
    arg3: 'text'
    // and so on up to 8
    arg8: 'end text'
    }
foo(obj);

So question is: is there any way for the function to get parameter object in a single var (args) AND have them destructured to be ready to use?

Barleby
  • 618
  • 2
  • 9
  • 20
  • 1
    Seems like "in a single var" AND "destructured" are opposites. Either the source object is destructured or it isn't. – Pointy Jan 10 '19 at 13:58
  • 1
    Not really, as you have to be explicit when destructuring about how many variables you use. But why would you want to do that? Destructuring a parameter object into a new variable for each key seems functionally the same as just referencing each key individually - e.g. having (essentially) `arg1 = args.arg1` followed by `this.model = arg1` and merely doing `this.model = args.arg1` are equivalent in function but cut one step. I suppose it's (slightly) more verbose the second way but I don't think you lose much clarity there. – VLAZ Jan 10 '19 at 14:00
  • you could assign `args` to `this`: `function foo(args) { Object.assign(this, args); }` – Nina Scholz Jan 10 '19 at 14:11
  • @vlaz you are right about the dot notation. I just wondered if I could avoid the extra 'args.' notation. This is, to reduce the args.arg1, args.arg2 to just: arg1 arg2 and so on. But I understand what you say – Barleby Jan 10 '19 at 14:37
  • @NinaScholz that's also a good approach. Unfortunately not all the properties are assigned to a unique object (this.model) – Barleby Jan 11 '19 at 08:53

1 Answers1

1

there are couple of ways to do it. the first one would be to store all argumens in a variable then do destruct it

function foo(...args){
  const  { arg1, arg2 } = args
   this.model = arg1;
   this.model = arg2;
   // and so on...
};

Or

function foo({ arg1, arg2 }){
   this.model = arg1;
   this.model = arg2;
   // and so on...
};
Tareq
  • 5,283
  • 2
  • 15
  • 18