0

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

2
  • dataKeyNames.split(',')? Then loop over the array and call .format() with the key's value? Commented Mar 10, 2014 at 20:12
  • 1
    @RocketHazmat I'm guessing they want it in "one" line. Where I'd guess using .map() on the split string, mixed with getting the respective values from the object, would give them the array they need to .apply to the function call Commented Mar 10, 2014 at 20:13

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick response. This worked a treat and is hardly any code.
@nfplee No problem! Just be away of the browser support for map: kangax.github.io/es5-compat-table/#Array.prototype.map - but the MDN page provides a polyfill in those few browsers that don't support it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.