4

Is there an easy (maybe even single and simple command) way to build a hashtable (associative array, JSON - whatever) from a string that includes key-value pairs, separated by a given delimiter.

Example:

n1=v1&n2=v2&n3=v3 (where & is a delimiter) should return: [{n1:v1}, {n2:v2}, {n3:v3}]

Example 2:

n1=v1;n2=v2;n3=v3 (where ; is a delimiter)

Thanks!

BreakPhreak
  • 10,940
  • 26
  • 72
  • 108
  • possible duplicate of [How can I convert query string or JSON object map to single JSON object with jQuery?](http://stackoverflow.com/questions/789755/how-can-i-convert-query-string-or-json-object-map-to-single-json-object-with-jqu) – mplungjan Jan 30 '12 at 12:53
  • That question is not quite the same as this question. Look at the difference in answers: none of the 7 versions of essentially the same code here is represented in the supposed duplicate. That said, I imagine there is an exact dupe somewhere. – Tim Down Jan 30 '12 at 13:05

10 Answers10

5

The following will do it in a pretty basic way and does a check that the key in each case is not empty. All values will be strings.

function parse(str, separator) {
    var parsed = {};
    var pairs = str.split(separator);
    for (var i = 0, len = pairs.length, keyVal; i < len; ++i) {
        keyVal = pairs[i].split("=");
        if (keyVal[0]) {
            parsed[keyVal[0]] = keyVal[1];
        }
    }
    return parsed;
}

Example:

var props = parse("n1=v1&n2=v2&n3=v3", "&");
alert(props.n2); // Alerts v2
Tim Down
  • 318,141
  • 75
  • 454
  • 536
3

Note: this yields the specified [{n1:'v1'}, {n2:'v2'}] format, and not the { n1: 'v1', n2: 'v2' } format that'd better fit the Hashtable description.

If you can trust your input in all other regards than the delimiter, then it would look something like this:

function splitByDelimiter(input, delimiter) {
    var parts = input.split(delimiter);
    var output = [];
    for(var i = 0; i < parts.length; i++) {
        var item = {};
        var keyValue = parts[i].split('=');
        item[keyValue[0]] = keyValue[1];

        output.push(item);
    }
    return output;
}

splitByDelimiter('n1=v1;n2=v2;n3=v3', ';')
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
3

Assuming you're using a modern browser:

str = "n1=v1&n2=v2&n3=v3"
delim = "&"

obj = str.split(delim).
    map(function(s) { return s.split("=") }).
    reduce(function(p, s) { return p[s[0]] = s[1], p }, {})

map, reduce

As a bonus, this also scales quite well when running in a cloud (see http://en.wikipedia.org/wiki/MapReduce).

georg
  • 211,518
  • 52
  • 313
  • 390
2
var stuff = "n1=v1&n2=v2&n3=v3".split("&"),
moreStuff = [],
hashStuff = {},
i = 0, l = stuff.length;

for (;i<l;i++) {
  moreStuff = stuff[i].split("=");
  hashStuff[moreStuff[0]] = moreStuff[1];
}
Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
2
var str = "n1=v1&n2=v2&n3=v3";

var arr = eval('[{' + str.replace(/=/g, ':"').replace(/&/g, '"},{') + '"}]');

or if you don't prefer eval

var arr = jQuery.parseJSON('[{"' + str.replace(/=/g, '":"').replace(/&/g, '"},{"') + '"}]')
Diode
  • 24,570
  • 8
  • 40
  • 51
2

My try, not a efficient one :(

query  = 'n1=v1&n2=v2&n3=v3'.split('&')
obj = {}

$.each(arr,function(k,v){
key = v.split('=')[0]
value = v.split('=')[1];
obj[key] = value;
})

obj.n1 outputs v1
Jashwant
  • 28,410
  • 16
  • 70
  • 105
1

Regular expressions.

See this summary from http://www.regular-expressions.info/javascript.html (Regexp Methods of The String Class section):

Using a string's split() method allows you to split the string into an array of strings using a regular expression to determine the positions at which the string is splitted. E.g. myArray = myString.split(/,/) splits a comma-delimited list into an array. The comma's themselves are not included in the resulting array of strings.

EDIT

You can refer to this other question too: Parse query string in JavaScript

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
1

Not 'easy' as in 'built-in', but...

var myQueryString = "n1=v1&n2=v2&n3=v3";
var delim = '&';

var vars = myQueryString.split(delim);

var parsed = {};
for (var i=0; i<vars.length; i++) { 
    var kvPair = vars[i].split("="); 
    parsed[kvPair[0]] = kvPair[1];
}

Result is in parsed.

izb
  • 50,101
  • 39
  • 117
  • 168
1
function parseStr2Map(str) {
    var elems = str.split("&");
    var map = {};
    for (var i = 0; i < elems.length; i++) {
        var nvPair = elems[i].split("=");
        map[nvPair[0]] = nvPair[1];
    }
    return map;
}

It's without errorhandling. If you want to parse location.search then you have to do the decode...

Nabor
  • 1,661
  • 3
  • 20
  • 45
1
var input = 'n1=v1&n2=v2&n3=v3';
var tokens = input.split('&');
var hashTable = {};

for (var i = 0; i < tokens.length; i++) {
    var keyValuePair = tokens[i].split('=');
    var key = keyValuePair[0];
    var value = keyValuePair[1];

    hashTable[key] = value;
}

alert(JSON.stringify(hashTable));
helpermethod
  • 59,493
  • 71
  • 188
  • 276