Last active
August 29, 2015 14:13
-
-
Save mygoare/f14149dca9325d50500e to your computer and use it in GitHub Desktop.
Convert javascript string to object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 临时解决方案而已 (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