1

is there a possibility to access ALL destructed function parameters in one object?

So I have this function head:

function coolFunctionName({test1 = "foo", test2 = "bar"})

I want to access them in one object. arguments doesn't work, because there aren't stored the default parameters which doesn't have a value in function call.

Is there a good and clean way to do that?

EDIT: I don't need the destructed parameters. I just want to have all of them in one object.

Vincent Hoch-Drei
  • 343
  • 1
  • 5
  • 14
  • 2
    Then don't destructure it in the argument list, rather receive it in (args = {}) object, and do what you have now inside the function body? – Arup Rakshit Sep 14 '18 at 14:31
  • Yeah, but I want to have default values. – Vincent Hoch-Drei Sep 14 '18 at 14:37
  • 2
    That you can do when destructuring inside the body also. In one word, what you asked is not yet possible in current JS . – Arup Rakshit Sep 14 '18 at 14:39
  • 1
    Destructuring allows to target individual variables, and it allows to give every target a default value. It does *not* create a new object, you will have to do that yourself. You cannot [destructure and construct an object literal at the same time](https://stackoverflow.com/q/25553910/1048572). – Bergi Sep 14 '18 at 14:44
  • Bergi. Ok, thank you, that's helpful. – Vincent Hoch-Drei Sep 14 '18 at 14:45

3 Answers3

2

Inspired from Faly's answer I think I've got the "cleanest" solution:

function coolFunctionName(options = {}){
    options = Object.assign({
        test1: "foo",
        test2: "bar
    }, options);
}

I have the parameter in one object and I have not to write multiple value names. I'm not happy about that because it's not in the function head but it's the best solution I've found.

Vincent Hoch-Drei
  • 343
  • 1
  • 5
  • 14
0

To achieve expected result, use below option of setting default value inside function

function coolFunctionName(x){
  x.test1 = x.test1 || 'foo'
  x.test2 = x.test2 || 'bar'
  console.log(x)
}
let z ={}
coolFunctionName(z);
let y ={test1:"zzz", test2:"yyy"}
coolFunctionName(y);

codepen- https://codepen.io/nagasai/pen/KxBmod?editors=1011

Naga Sai A
  • 9,949
  • 1
  • 15
  • 34
  • Nope, the values are ALWAYS `test1: "foo"` and `test2: "bar"`. – Vincent Hoch-Drei Sep 14 '18 at 14:56
  • @VincentHoch-Drei, there should be a check to check if parameters have any values or not and then assign default values, updated my codepen - https://codepen.io/nagasai/pen/KxBmod?editors=1011 and answer – Naga Sai A Sep 14 '18 at 15:01
  • @VincentHoch-Drei, updated and made it simple and works in all browsers, if you use Object.assign, you may need to use polyfill - https://github.com/mozilla-services/react-jsonschema-form/issues/206 – Naga Sai A Sep 14 '18 at 15:14
-1

All you can do is:

function coolFunctionName({test1 = "foo", test2 = "bar"}) {
    let arguments = { test1, test2 };
    /* Do whatever you want with arguments */
}
Faly
  • 12,529
  • 1
  • 16
  • 34