Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: unpack object as function parameters

I have a function, in Javascript

function asd(foo, bar, baz) {
    // ...
}

And each of those 3 arguments is required.

Suppose I have those arguments grouped as an object:

var x = {
    foo: 10,
    bar: 20,
    baz: 30
};

Can I call function asd just by giving object x somehow "unpacked"? Can this be done generically? i.e., not knowing the signature of asd.

I'm searching for something like kwargs unpacking in Python:

def asd(foo, bar, baz):
    # ...

kwargs = {'foo': 10, 'bar': 20, 'baz': 30}
asd(**kwargs)

A "no, not possible" answer is acceptable. I just want to know whether this is possible in Javascript.

like image 624
André Staltz Avatar asked Feb 23 '14 14:02

André Staltz


2 Answers

This is now possible in JavaScript. The other comment stating that it is not possible natively is not correct (and wasn't at time of posting). It was added roughly a year after you asked - adding an answer for people landing here many years later.

Your function simply needs to change to:

function asd({foo, bar, baz}) {
    // ...
}

and you call it like this:

var x = {
    foo: 10,
    bar: 20,
    baz: 30
};
asd(x);

See MDN Destructuring Assignment.

like image 80
Aaron J Avatar answered Nov 04 '22 14:11

Aaron J


function asd(foo, bar, baz) {
    console.log(foo, bar, baz);
}

var x = {
    foo: 10,
    bar: 20,
    baz: 30
};

var args = [];
for(var i in x){
    args.push(x[i]);
}
asd.apply(window, args);

But, like other people said, ordering is a problem. With for in you get the properties in the order that they were defined. If that's what you want, then this solution can work for you. But mapping parameters by name is not possible.

like image 25
spassvogel Avatar answered Nov 04 '22 14:11

spassvogel