我想弄清楚如何将字符串转换为对象。分隔符是|
字符。所以本质上是这样的:
var myString = "Name, Bob | Location, Washington | Pet, Dog";
变成:
var myObj = {
Name: "Bob",
Location: "Washington",
Pet: "Dog"
};
提前感谢您提供任何有用的意见。
我想弄清楚如何将字符串转换为对象。分隔符是|
字符。所以本质上是这样的:
var myString = "Name, Bob | Location, Washington | Pet, Dog";
变成:
var myObj = {
Name: "Bob",
Location: "Washington",
Pet: "Dog"
};
提前感谢您提供任何有用的意见。
假设字符串格式正确,这将起作用(您需要在旧浏览器中使用SHIM forEach,或将其替换为循环):
var myString = "Name, Bob | Location, Washington | Pet, Dog";
var myObj = function(){
var result = {};
myString.split(/\s*\|\s*/).forEach(function(el){
var parts = el.split(/\s*,\s*/); result[parts[0]] = parts[1];
});
return result;
}();