简体   繁体   English

JavaScript将String转换为对象

[英]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 人们使用js库(例如underscoreunderscore.stringlodash ,将以下String转换为Object

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

The following are constant: animals and fish . 以下是不变的: animalsfish 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. animalsfish可以以任何顺序出现在弦中。

Thanks! 谢谢!

PS Its not a duplicate of Parse query string in JavaScript ... as the requirements are to return an object for later parsing... PS它不是JavaScript解析查询字符串的重复...因为要求是返回一个对象以供以后解析...

Quick vanilla js solution: 快速香草js解决方案:

 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. 使用split功能分割字符串,该功能split保留拆分器,这些split器是拆分正则表达式中的组。 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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