Magnus
Magnus

Reputation: 7829

Spreading Object Arguments

With the spread syntax, we can expand an array function argument, into distinct parameter variables:

var mySpreader = function (nk, mk, zk) {
    console.log('Spread parameter 1: ' + nk);
    for (let v in arguments){
        console.log('Spread parameter: ' + arguments[v]);
    }
};

var spreadArr = ['a', 'b', 'c'];
mySpreader(...spreadArr);

Question 1: Why is it not possible to spread object arguments in the same way? The following throws an error:

var spreadObj = {mk: 'm', nk: 'n', zk: 'z'};
mySpreader(...spreadObj);

To "fix" the above, it seems we have to use a destructuring assignment to emulate a "spreading":

var myDestructor = function ({nk, mk, zk}) {
    console.log('Destructioned parameter: ' + nk);
    for (let v in arguments[0]){
        console.log(v);
        console.log(arguments[0][v]);
    }
};

myDestructor({mk: 'm', nk: 'n', zk: 'z'});

Question 2: The loop in myDestructor did not work for accessing the destructured variables. Instead, the loop treated the incoming data as a full (non-destructured) object. That was (kind-of) expected. Is there any way to loop through the destructured distinct parameter values?

Upvotes: 2

Views: 523

Answers (1)

Bergi
Bergi

Reputation: 665130

Why is it not possible to spread object arguments in the same way?

Spreading is for iterable stuff, to use an array for positional parameters. Objects are not iterable - they don't even have an order!

The loop in myDestructor just treated the incoming data as a full (non-destructured) object. Any idea why?

Well, because the incoming data - the argument that your function was called with - is an object. arguments[0] is an object. That you have multiple variables initialised from its properties right in the parameter declaration is just syntactic sugar. You could equally have written function (o) { var {nk, mk, zk} = o; instead of function ({nk, mk, zk}) {.

Upvotes: 1

Related Questions