1

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")

1 Answer 1

5

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));
Sign up to request clarification or add additional context in comments.

9 Comments

The ajax php give me data like {"function":{"append":{"element":"test","url":"test"}}} which is outputted as json data. Which I want to use to call the function.
Thanks for your help. I tried your method but it just gives me a comma separated string for message and url is still undefined.
Oh, it's the .message property that has the object whose values you're looking for, see edit
I need the object values Message and Url to correspond to the function Append parameters(Message,Url)
I added an edit. Maybe it can explain it a bit better! Thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.