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!
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With