简体   繁体   中英

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? ie, 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.

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 .

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.

Just making things clearer for people coming from Google like me:

No, this is not possible natively in JavaScript.

You have to implement something custom to achieve this (see the other answer).

Answring to this old post, I implemented this solution that relies on the spread operator and on parsing the function argument names. It can be improved to accept also arrow function.

 Function.prototype.kwargs = function(argsObj){ const rawArgs = this.toLocaleString().match(/\\(.*\\)\\{/); if(!rawArgs){ console.error("args parsing failed"); return; } const argsList = rawArgs[0].replace(/\\(|\\)|\\{/g, '').split(','); const args = argsList.map((param) => argsObj[param.trim()] || param); return this(...args); } function sum(a,b){ return a+b; } const input = {a:1, b:2} console.log(sum.kwargs({a:1, b:2})) function sum2(a12, b){ return a12+b; } const input2 = {a12:1, b:2}; console.log(sum2.kwargs(input2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM