Maciek
Maciek

Reputation: 1972

Convert object into parameters for function

I have a AJAX with php that outputs different functions to run on the jquery side of things.

$.each(data['function'],function(key,value){
  window[key](value)
}

data['function'] contains function data to run.

For example:

{"append":{"message":"hello","url":"link.com"}}

Will activate function

function append(message,url){...}

The problem is that {"message":"hello","url":"link.com"} is all contained in message. How can I translate or convert {"message":"hello","url":"link.com"} as parameters for the function?

right now it's running like this:

append({"message":"hello","url":"link.com"},undefined)

What is the solution to enable it to run like this:

append("hello","link.com")

I want to keep parameters intact append(message,url) and not resort to a single parameter method. I can't quite find a good solution.

Edited (Simplified)

How can I change Params object:

var Params={"message":"hello","url":"link.com"}
window['append'](Params);

To run the same as:

window['append']("hello","link.com")

Upvotes: 1

Views: 1615

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

Spread the values of the data['function'] object into the parameter list of the function you want to call:

append(...Object.values(data.function.message));

The old way to do it would be to use .apply instead:

append.apply(undefined, Object.values(data.function.message));

Note that it's pretty confusing to have an object inside a key named function - one would probably expect a function to be there instead. You might consider a different property name, such as parametersObj or something of the sort.

If the function name is dynamic as well (which is a code smell), then use Object.entries to get both the key (function name) and value (object) at once:

const [fnName, obj] = Object.entries(data.function);
window[fnName](...Object.values(obj));

Upvotes: 5

Related Questions