How to parse a row into a hash table

Is there a simple (possibly simple and simple) way to construct a hash table (associative array, JSON - independently) from a string containing key-value pairs separated by this separator.

An example :

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

Example 2 :

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

Thanks!

+4
source share
10 answers

The following will do this in a fairly simple way and verify 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 
+5
source

Note. . This gives the format [{n1:'v1'}, {n2:'v2'}] rather than the format { n1: 'v1', n2: 'v2' } , which better matches the Hashtable description.

If you can trust your input in all other respects except the delimiter, then it will 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', ';') 
+3
source

Assuming you are 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, it also scales pretty well when working in the cloud (see http://en.wikipedia.org/wiki/MapReduce ).

+3
source
 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]; } 
+2
source
 var str = "n1=v1&n2=v2&n3=v3"; var arr = eval('[{' + str.replace(/=/g, ':"').replace(/&/g, '"},{') + '"}]'); 

or if you do not prefer eval

 var arr = jQuery.parseJSON('[{"' + str.replace(/=/g, '":"').replace(/&/g, '"},{"') + '"}]') 
+2
source

My attempt, not effective :(

 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 
+2
source

Regular expressions.

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

Using the split split () method splits a string into an array of strings using a regular expression to determine the positions at which the string is split. For instance. myArray = myString.split (/, /) splits a comma-delimited list into an array. The comma itself is not included in the resulting array of strings.

EDIT

You can also address this other question: JavaScript parsing query string

+1
source

Not "easy" as in the "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]; } 

The result is in parsed .

+1
source
 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 is error-free. If you want to parse location.search you need to decode ...

+1
source
 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)); 
+1
source

Source: https://habr.com/ru/post/1393757/


All Articles