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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With