5

I am trying to generate javascript object array to urlstring like:

var array = [{'name': 'foo', 'value': '2'},
             {'name': 'foo', 'value': '2,8'},
             {'name': 'foo', 'value': '2,10,3'}
            ];

// url ==> foo=2&foo=2,8&foo=2,10,3
2
  • I believe this might be possible, with a little bit of effort. What have you tried? Commented Nov 3, 2014 at 15:20
  • I tried $.param(array) but not it is not working Commented Nov 3, 2014 at 15:22

6 Answers 6

9

To be safe, you'd want to encode the component pieces:

const array = [
  {'name': 'foo', 'value': '2'},
  {'name': 'foo', 'value': '2,8'},
  {'name': 'foo', 'value': '2,10,3'}
];

const parts = array.map((param) => {
  return(
    encodeURIComponent(param.name) + '=' +
    encodeURIComponent(param.value)
  );
});

const url = parts.join('&');

console.log(url);

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

Comments

6

You can do this

var url = "";
array.forEach(function(e){
   url += e.name + "=" + e.value + "&";
});
url = url.trim("&");

Comments

2

You'll need to loop through the array, determine whether the array entry is the first or not (so that they will be separated with ampersands, and use the JSON field names.

var queryString = "";
for ( var i = 0; i++; i < array.length ) {
    if ( i > 0 ) {
        queryString = queryString + "&";
    }
    queryString = queryString + array[i]["name"] + "=" + array[i]["value"];
}

Comments

1

Try this code:

var array = [{'name': 'foo', 'value': '2'},
             {'name': 'foo', 'value': '2,8'},
             {'name': 'foo', 'value': '2,10,3'}
            ];
var output = "";

for(var i = 0; i < array.length; i++){
    output = output + array[i].name+"="+array[i].value+"&"
}

output = output.substring(0, output.length-1);
alert(output)

Here the fiddle

Comments

1

If your array contains object with parameters 'name' and 'value', you should use:

$.param(array)

http://api.jquery.com/jquery.param/

Comments

0

No need loops and aux vars, Array built-in methods do it.

Array.map + Array.join:

> array.map(p => p.name + '=' + p.value).join('&')
'foo=2&foo=2,8&foo=2,10,3'

> array.map(function(param){
    return param.name + '=' + param.value
  }).join('&')
'foo=2&foo=2,8&foo=2,10,3'

safe use (but not expected OP's output):

> array.map(p => encodeURIComponent(p.name) + '=' + encodeURIComponent(p.value)).join('&')
'foo=2&foo=2%2C8&foo=2%2C10%2C3'

Comments

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.