Skip to content

Instantly share code, notes, and snippets.

@mygoare
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save mygoare/f14149dca9325d50500e to your computer and use it in GitHub Desktop.

Select an option

Save mygoare/f14149dca9325d50500e to your computer and use it in GitHub Desktop.
Convert javascript string to object
// 临时解决方案而已 (It is not a good part code)
var convertStrToObj = function(str)
{
var val = str.slice(1, -1);
var properties = val.split(', ');
var obj = {};
properties.forEach(function(property) {
var index = property.indexOf(':');
var pre = property.slice(0, index).trim();
var aft = property.slice(index + 1).trim().slice(1, -1);
obj[pre] = aft;
});
return obj;
};
////////
var str = "{a: '1', b: 'abc'}";
var convertObj = convertStrToObj(str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment