JavaScript Array to URLencoded

亡梦爱人 提交于 2019-12-01 03:19:29

You can do something like this:

var myData = new Array('id=354313', 'fname=Henry', 'lname=Ford');
var url = myData.join('&');
jgrund

Try this:

var myData = {'id': '354313', 'fname':'Henry', 'lname': 'Ford'};
var out = [];

for (var key in myData) {
    if (myData.hasOwnProperty(key)) {
        out.push(key + '=' + encodeURIComponent(myData[key]));
    }
}

out.join('&');

For an explanation about why use hasOwnProperty, take a look at this answer to "How do I loop through or enumerate a JavaScript object?".

Eduard Brokan

If you use jQuery, can use $.param(). Check here . Example of using

var myData = {'id' : '354313', 'fname' : 'Henry', 'lname' : 'Ford'};
var url = "https://stackoverflow.com?" + $.param(myData);

Output is

https://stackoverflow.com?id=354313&fname=Henry&lname=Ford

Also works with an array of objects (like from jQuery(form).serializeArray()) :

var myData = [{'id' : '354313'}, {'fname' : 'Henry'},{'lname' : 'Ford'}];

If you use an object instead of an array you can do this (ES6) :

var myData = {
    id: 354313,
    fname: 'Henry',
    lname: 'Ford',
    url: 'https://es.wikipedia.org/wiki/Henry_Ford',
};

encodeDataToURL = (data) => {
    return Object
      .keys(data)
      .map(value => `${value}=${encodeURIComponent(data[value])}`)
      .join('&');
 }

console.log(encodeDataToURL(myData));
var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param( myObject );
var recursiveDecoded = decodeURIComponent( $.param( myObject ) );

alert( recursiveEncoded );
alert( recursiveDecoded );

The values of recursiveEncoded and recursiveDecoded are alerted as follows:

a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3 a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

https://api.jquery.com/jQuery.param/

Look at the function escape and unescape.

Taken from jgrunds answer, if you want to extend the array functionality

Array.prototype.toQueryString = function(){
    var out = new Array();

    for(key in this){
        out.push(key + '=' + encodeURIComponent(this[key]));
    }

    return out.join('&');
}

Or if you want a standalone function

function arrayToQueryString(array_in){
    var out = new Array();

    for(var key in array_in){
        out.push(key + '=' + encodeURIComponent(array_in[key]));
    }

    return out.join('&');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!