Monday 13 November 2017

javascript - How to parse a string into a hashtable

itemprop="text">


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!



Answer




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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...