nfplee
nfplee

Reputation: 7997

Pass an Array in as Arguments to Function

I have the following function:

String.prototype.format = function() {
    var args = arguments;

    return this.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != 'undefined' ? args[number] : match;
    });
};

Now say I have the following code defined:

var dataItem = { membershipId: 1, userId: 3 };
var dataKeyNames = 'membershipId,userId';
var url = '/Admin/User?MembershipId={0}&UserId={1}';

What I'd like to do is call the format function passing in each value from the data item (for each data key name). For example if there was only one data key name then I would be able to say:

var formattedUrl = url.format(dataItem[dataKeyNames]);

But I need to be able to do a split on the dataKeyNames and pass each corresponding value from the data item in as arguments in the format function.

I'd appreciate it if someone could show me how this is done. Thanks

Upvotes: 0

Views: 89

Answers (1)

Ian
Ian

Reputation: 50933

Let's take this one step at a time.

First, you can split the string of keys into an array, using dataKeyNames.split(",").

Then, you can call map on the array of strings to generate a new array - specifically, the values that you want to pass to your format method. This is where you interact with the dataItem variable.

Finally, you can use url.format.apply to actually call your format method with the new array. Note that it's possibly most important to pass url as the first argument to apply - that sets the this value that format will use.

Here's the code I came up with:

var formattedUrl = url.format.apply(url, dataKeyNames.split(",").map(function (val, index, array) {
    return dataItem[val];
}));

DEMO: http://jsfiddle.net/T4tHx/

To make it more readable, you can definitely split this up into several lines.


References:

Upvotes: 2

Related Questions