Aaron
Aaron

Reputation: 2500

Passing in String to jQuery function as Object

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

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

The above is saved to a string named args. Nothing special, but I'm wanting to pass it in as an argument to a function.

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

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

Upvotes: 3

Views: 2235

Answers (2)

travega
travega

Reputation: 8415

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

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

And then pass the "args" variable into your function.

Upvotes: 1

Plynx
Plynx

Reputation: 11461

If you really have a string such as this:

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

You can parse it using JSON.parse and get an object out of it like so:

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

But in reality you probably want to just create such an object instead of a string from the start, e.g.:

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

Upvotes: 3

Related Questions