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?
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
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments