0

I'm receiving the following object for example:

var object = {
    functions: {
        0: 'myFunction',
        1: 'alert'
    },
    parameters: {
        0: {
            0: 'Testing myFunction...'
        },
        1: {
            0: 'Testing alert...'
        }
    }
}

After receiving object variable I want to run all the functions specified with the corresponding parameters.

That is, after receiving the object I want the following to happen:

myFunction('Testing myFunction');
alert('Testing alert');

Is there an elegant way of handling this or is stringconversion into eval the way to go? Some other methods I don't know about?

Weblurk
  • 6,562
  • 18
  • 64
  • 120
  • 2
    like this? `object.functions['0'](object.parameters['0']['0']);`, you can easily convert it into a generic function, if you can see the pattern with the numbering :) – epoch Apr 07 '14 at 14:18
  • 1
    Can the items of _parameters_ not be _Arrays_? – Paul S. Apr 07 '14 at 14:24
  • Possible duplicate of http://stackoverflow.com/questions/7424476/call-jquery-defined-function-via-string – Smeegs Apr 07 '14 at 14:25

1 Answers1

3

Simply loop over object.functions, and use .apply call it with its parameters from object.parameters.

for(var i in object.functions){
    if(object.functions.hasOwnProperty(i)){
        // Convert object.parameters[i] to an array
        var params = [];
        for(var j in object.parameters[i]){
            if(object.parameters[i].hasOwnProperty(j)){
                params.push(object.parameters[i][j]);
            }
        }
        // Call the function with an array of params
        window[object.functions[i]].apply(null, params);
    }
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • +1, nice solution, I was about to comment on using `slice` with objects, haha – epoch Apr 07 '14 at 14:25
  • 1
    I tried doing `Array.prototype.slice.call(object.parameters[i])`, but it didn't work. I think it needs a `.length` property to be able to do that. – gen_Eric Apr 07 '14 at 14:26
  • 1
    I would strongly suggest that there is another _Object_ which holds references to the functions so that you're not looking in `window`, but other than that this is the way to go – Paul S. Apr 07 '14 at 14:28
  • @RocketHazmat Thanks for the answer. I haven't tested it yet but reading through your code I'm wondering, shouldn't I reset the params array in the end of the loop, after the window|object....]-line? – Weblurk Apr 07 '14 at 14:36
  • 1
    @Weblurk: What do you mean by "reset the params array"? It's set to `[]` each time the outer loop (`object.functions`) runs. – gen_Eric Apr 07 '14 at 14:37
  • You're right, my mistake. Thought it was set outside the loop for some reason. – Weblurk Apr 07 '14 at 14:43
  • 1
    It's alright :-) Glad I could be of assistance :-D – gen_Eric Apr 07 '14 at 14:47