0

Say I have an array of arrays(key/value) that are dynamically generated:

var parameters = [ ['Key1','value1'],['key2','value2'],['key3','value3']];

and I have a function that accepts a dynamic amount of arguments via the arguments object

function somefunction(){
    var args = [];
    var len = arguments.length
    for(var i=0;i<len;i++)
    {
        args[i] = arguments[i];
    }

How do I call the function with parameters variable so that each item in the array is considered an argument example:

somefunction(['Key1','value1'],['key2','value2'],['key3','value3']);

instead of:

somefunction([['Key1','value1'],['key2','value2'],['key3','value3']]);

which is what

somefunction(parameters);

sends

James
  • 409
  • 2
  • 4
  • 18
  • 2
    Read about [`Function.apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) – axiac Apr 10 '18 at 15:44
  • 1
    @manikantgautam https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments – axiac Apr 10 '18 at 15:44

1 Answers1

4

You can use apply :

somefunction.apply(null, parameters);

If you can use ES6, the rest operator ... will works too:

somefunction(...parameters);
Magus
  • 14,796
  • 3
  • 36
  • 51
  • sadly I couldn't use the rest operator as I need to maintain compatibility with IE, but the apply works – James Apr 10 '18 at 16:08