本文介绍了如何将字符串解析为哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法(甚至是简单的命令),即可从包含键值对并由给定分隔符分隔的字符串中构建哈希表(关联数组,JSON等).
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.
示例:
n1=v1&n2=v2&n3=v3
(其中&
是分隔符)应该返回:[{n1:v1}, {n2:v2}, {n3:v3}]
n1=v1&n2=v2&n3=v3
(where &
is a delimiter)should return: [{n1:v1}, {n2:v2}, {n3:v3}]
示例2 :
n1=v1;n2=v2;n3=v3
(其中;
是分隔符)
谢谢!
推荐答案
以下内容将以非常基本的方式进行操作,并检查每种情况下的键都不为空.所有值都是字符串.
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;
}
示例:
var props = parse("n1=v1&n2=v2&n3=v3", "&");
alert(props.n2); // Alerts v2
这篇关于如何将字符串解析为哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!