0

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?

1
  • 1
    I believe you want functionCall.apply(null, objects) but the objects must be an array for that. Commented Mar 31, 2015 at 1:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just realized you answered this I guess a split second sooner... Thank you also.
1

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.

2 Comments

Ahh, thank you! For some reason I expected that to return it as an array not as separate objects. I have to wait 5 minutes to accept your answer but I will. Thanks again.
That's what happens if you just call the function normally. The whole point of .apply is to spread the array.

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.