Charlie Burns
Charlie Burns

Reputation: 7044

How to refer to unnamed destructured parameters in ES6?

In the code below, I'm wondering if there is something to replace magic that will do the same thing as the call to foo just above it.

function foo(a, { b=0, c=1 } = {} ) {
    console.log(a, b, c);
}
function bar({ b=2, c=3 } = {} ) {
    foo(99, { b:b, c:c });
//  foo(99, magic); // should be equivalent to the above call
}
bar({c:4});

Reason being I have a function where the unnamed object parameter is quite large and it seems like a shorthand would look nicer and be less error prone than writing all the object keys each time. (I'm porting a library from python to ES6 and trying to maintain the existing api as much possible. )


Edit: Another way to ask this is: "Is there a way to loop through these parameters b and c without knowing their names?"


Edit2: Here's the real code looks like. Functional but ugly. Must be a better way.

function Decoder({
    encoding="utf-8",
    object_hook=echo,
    parse_float=Number,
    parse_int=Number,
    parse_constant=Number,
    strict=true,
    object_pairs_hook=echo} = {}) {

    if(!(this instanceof Decoder)) {
        return new Decoder({
            encoding:encoding,
            object_hook:object_hook,
            parse_float:parse_float,
            parse_int:parse_int,
            parse_constant:parse_constant,
            strict:strict,
            object_pairs_hook:object_pairs_hook});
    }
    this.encoding = encoding;
    this.object_hook = object_hook;
    this.parse_float = parse_float;
    this.parse_int = parse_int;
    this.parse_constant = parse_constant;
    this.strict = strict;
    this.object_pairs_hook = object_pairs_hook;
}

Upvotes: 1

Views: 111

Answers (1)

sdgluck
sdgluck

Reputation: 27237

Perform the destructure inside the function. Something like this:

function bar(obj) {
  const { b = 2, c = 3 } = obj
  const magic = { b, c }
  foo(99, magic); // abracadabra
}

Upvotes: 1

Related Questions