Passing jQuery function to String as object

It might be a stupid question, but I'm trying to pass a string of settings I built in the following format:

"setting1" : "value", "setting2" : "value", "setting3" : "value"

      

The above is stored in a string named args. Nothing fancy, but I want to pass it as a function argument.

$('#element').functionName({ args });

      

I'm not sure what I'm missing here ... Thanks!

+3


source to share


2 answers


If you actually have a line like:

'"setting1" : "value", "setting2" : "value", "setting3" : "value"'

      

You can parse it with JSON.parse

and get an object from it like this:



var args = JSON.parse( "{" + str + "}" );
$('#element').functionName(o);

      

But in reality, you probably want to just create an object like this instead of a string from the beginning, like this:

var args = {"setting1" : "value", "setting2" : "value", "setting3" : "value"};
$('#element').functionName(args);

      

+3


source


There is no such thing as a stupid question. Try:

var args = JSON.parse("{'setting1' : 'value', ...}");

      



And then pass the args variable to your function.

+1


source







All Articles