0

If I have an object array like this...

var p = [{ 'first': 'John', 'last': 'Doe' }, { 'first': 'Sue', 'last': 'Smith' }];

And I need to append it to the URL like this...

/myapp/myaction?p[0].first=John&p[0].last=Doe&p[1].first=Sue&p[1].last=Smith

Is there something in JQuery that will help me do this without having to process it manually?

Basically, I have an object like the people array, and I need to send it to ASP MVC3 in a format that it will understand and bind to a list. MVC3 understands nested items encoded in the "dot" format (e.g. p[0].first).

2
  • 2
    FYI { first='John', last='Doe' } is not a valid JSON object, it should be at least { 'first':'John', 'last':'Doe' } Commented Apr 24, 2012 at 19:59
  • Thanks, I was writing quickly and did not check the code. I will update the question. Commented Apr 25, 2012 at 14:35

1 Answer 1

2

There may be an even better way, but something like this should work:

var params = $.map(p, function(n, i){
    return "p[" + i + "].first=" + n.first + "&p[" + i + "].last=" + n.last;
}).join("&");

If the properties of the objects are dynamic, you could use a for...in to loop over them.

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

1 Comment

Thanks! This worked well. I was thinking there might be an existing method in JQuery that might do this, but this was super easy.

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.