Reputation: 375
I have a string of javascript objects that I need to convert to function arguments.
The string looks like this:
"{ "item1": "foo 1", "item2": "bar 1" }, { "item1": "foo 1", "item2": "bar 2" }"
I can concat "[ ]" and call JSON.parse to turn it into a valid array however, this does not solve my problem since the function needs them to be separate objects not an array of objects.
EX:
functionCall({ "item1": "foo 1", "item2": "bar 1" }, { "item1": "foo 1", "item2": "bar 2" });
I will never know how many objects will be in this string so I do not know how many arguments the function should accept either.
I would love to be able to add multiple objects to one variable like:
var objects = { "item1": "foo 1", "item2": "bar 1" }, { "item1": "foo 1", "item2": "bar 2" }
and then I could just call
functionCall(objects);
Is there a way to accomplish something like this or another approach I can take?
Upvotes: 0
Views: 841
Reputation: 780724
You can use Function.prototype.apply
to convert an array into function arguments:
functionCall.apply(null, objects);
The initial null
argument is the this
argument for the function; if you're not calling an object method, it's not needed and null
can be used as a placeholder.
Upvotes: 1
Reputation: 9157
You can use Function.prototype.apply()
:
functionCall.apply(window, objects);
(Replace window
with whatever scope you'd like the function to have.)
The second argument is an array of objects, so go ahead and put the objects in an array and then use apply
.
Upvotes: 1