AKG
AKG

Reputation: 3296

Convert parameter object with dynamic number of variables to multiple paramaters

I've got an object holding parameters for a function. However, I would like to convert this into a list of multiple parameters. To illustrate this, the code below:

So I've got this:

var args = {one: 'apple', two: 'banana', three: 'kiwifruit'};
function(args) {
}

And I would like to see args converted into some way so I can use it like this:

function(one, two, three) {
}

That wouldn't be a problem if the number of variables in args was static. However, in my case, the number of variables is dynamic.

I know I can get a comma-delimited list using the .join() method. However, as this is a string, it is not usable. I even tried using Number() on the string. Could anyone nudge me in the right direction?

Upvotes: 1

Views: 129

Answers (3)

nils
nils

Reputation: 1668

If I understand you right, this should answer your question:

function foobar(one, two, three) {
  ...
}

var args = {one: 'apple', two: 'banana', three: 'kiwifruit'};

// call foobar() and pass arguments one by one
foobar(args.one, args.two, args.three);

You can also convert you object to an array und call your function with Array.apply()

var params = [];

for (key in args) 
{
  params.push(args[key]);
}

foobar.apply(this,params);

Both ways are totally fine. If you do not need to pass a dynamic number of arguments I would recommend passing each param separately because it will be much easier for other developers to understand which params are passed to the function.

Upvotes: 1

Geert-Jan
Geert-Jan

Reputation: 18925

For dynamic lists of parameters (i.e.: those that you don't know at design time) use function.apply

This allows you to pass an array of values as a a list of multiple parameters as you describe it yourself.

So:

  1. convert object into array of values
  2. pass array of values to function.

Given :

var args = {one: 'apple', two: 'banana', three: 'kiwifruit'};
var f = function(one, two, three) {
}

Then 1:

var values = [];
for (key in args) {
  values.push(args[key]);
}
//or use underscore / lodash and do values = _.values(args);

And 2.

f.apply(this,values)

Upvotes: 1

progysm
progysm

Reputation: 1072

Calling a function f with three args. The problem here is that Object.keys doesn't assure the keys order. So you could end up with args.one in the argument "two".

function f(one, two, three) {
    console.log(one, two, three);
}

var args = {one: 'apple', two: 'banana', three: 'kiwifruit'};
var newArgs = Object.keys(args).map(function(el) {
    return args[el];
});

// call f sending the list of values, show apple, banana, kiwifruit in the console
f.apply(null, newArgs);

Jsfiddle: http://jsfiddle.net/3N8tC/

Upvotes: 1

Related Questions