简体   繁体   中英

JavaScript convert String to object

Folks, using js libraries such as underscore , underscore.string , or lodash , I'd like to convert the following String to an Object

'animals=cat&dogs&horses&fish=salmon&tuna';

The following are constant: animals and fish . Separator is =

The result should look like:

{
    animals: 'cats&dogs&horses',
    fish: 'salmon&tona'
}

animals and fish can occur in the string in any order.

Thanks!

PS Its not a duplicate of Parse query string in JavaScript ... as the requirements are to return an object for later parsing...

Quick vanilla js solution:

 function parseQuery (string) { var result = {}, components, i, firstPair, current; components = string.split("&"); for (i = 0; i < components.length; i++) { if (components[i].indexOf("=") !== -1) { if (typeof current !== "undefined") { result[current] = result[current].join("&"); } firstPair = components[i].split("="); current = firstPair[0]; result[current] = [firstPair[1]]; } else { result[current].push(components[i]); } } result[current] = result[current].join("&"); return result; } 

This is a bit more compact:

var x = 'animals=cat&dogs&horses&fish=salmon&tuna';

Split the string using the feature of split which preserves splitters which are groups in the splitting regexp. We split on anything which starts at the beginning of the string or with a & , and contains an = at the end:

var pieces = x.split(/((?:^|&)\w+=)/) . filter(Boolean);
>> ["animals=", "cat&dogs&horses", "&fish=", "salmon&tuna"]

The result will be an array of interspersed keynames and values. Process this into an object:

var result = {};
for (var i=0; i<pieces.length; i+=2) { 
    result[pieces[i].replace(/^&|=$/g, '')] = pieces[i+1];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM