Skip to content Skip to sidebar Skip to footer

How Parameterize Array To As Single Comma Separated Value?

How can I parameterize an array so that it's a single name value pair that's comma separated. Using jQuery $.param creates a parameter for each array value instead of just one. And

Solution 1:

At its simplest, and assuming the value of each property of the object is an array:

function param(obj) {
    var output = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            output.push(prop + '=' + obj[prop].join(','));
        }
    }
    return output.join('&');
}

var p = {
    a: [2, 3, 4],
    b: ['something','else']
};
console.log(param(p)); //a=2,3,4&b=something,else

JS Fiddle demo.

Solution 2:

I think you're going to have to create this function bespoke. Fortunately if your data structure is that simple then it's not too difficult:

var p = {a: [2, 3, 4]};
var encoded = '';

for (var prop in p) { 
  if (p.hasOwnProperty(prop)){
    encoded += prop + '=' + p[prop].join();
  }
}

Post a Comment for "How Parameterize Array To As Single Comma Separated Value?"