0

I often find myself writing code like this:

function handleSomeEvent(p1, p2, p3) {
  var data =  { p1: p1, p2: p2, p3: p3 };

  //Or any other function that takes an object
  $.ajax('/url', { data: data, ... });
}

Is there a way that I can build the data object automatically from my function's parameters?

I know that I could pass in an object instead, but sometimes it's more convenient to pass in multiple parameters (for example integrating with legacy code, or a project's existing coding style).

joews
  • 29,767
  • 10
  • 79
  • 91

3 Answers3

0

I'd do this using the arguments object in javascript. Every function has an arguments array which can be enumerated as below.

var data = {};
for(var i=0; i<arguments.length; i++) {
   data["var" + i] = arguments[i];
}
Captain John
  • 1,859
  • 2
  • 16
  • 30
  • I don't want to enumerate over them, though - I want control over the names of my object's members. – joews Dec 09 '13 at 20:40
0

Based on @HaukurHaf's link, I have pulled this together (using Underscore.js):

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function getParamMap(func, funcArgs) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '')
  var names = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(/([^\s,]+)/g)
  if(names === null)
     names = []
  args = Array.prototype.slice.call(funcArgs);
  return _.object(_.zip(names, args));
}

function example(a, b, c, d) {
    return getParamMap(example, arguments);
}

console.log(example(1,2,3, "hello"));
// -> Object {a: 1, b: 2, c: 3, d: "hello"} 

http://jsfiddle.net/rGtu7/2

Works in Chrome, Firefox and IE11, but I was really hoping for a more elegant solution. It would be cool if Javscript supported reflecting over argument names.

joews
  • 29,767
  • 10
  • 79
  • 91
0

ES2015 shorthand object literals reduce some of the repetition:

function handleSomeEvent(a, b, c) {
  console.log({ a, b, c })
}
joews
  • 29,767
  • 10
  • 79
  • 91