Skip to content

Instantly share code, notes, and snippets.

@wgottschalk
Created January 16, 2016 22:27
Show Gist options
  • Save wgottschalk/323f603400728eaf8ae6 to your computer and use it in GitHub Desktop.
Save wgottschalk/323f603400728eaf8ae6 to your computer and use it in GitHub Desktop.
function buildObject(str) {
var newObj = {};
var newKey, newVal;
var elstart = 1;
var elend = 1;
var contentsStr = str.substring(1,str.length-1);
contentsStr = contentsStr.trim();
var contentsLength = contentsStr.length;
if (contentsLength === 0) {
console.log('broke out');
return newObj;
}
for (var i = 0; i < str.length; i++) {
if (str[i] === ':') {
elend = i;
if (elend - elstart > 0) {
newKey = str.substring(elstart,elend).trim();
newKey = returnTerminalDatatype(newKey);
}
elstart = i+1;
}
if (str[i] === '}' || str[i] === ',') {
elend = i;
if (elend - elstart > 0) {
newVal = str.substring(elstart,elend).trim();
newVal = parse(newVal); //parse is a helper function
}
elstart = i+1;
}
newObj[newKey] = newVal;
}
return newObj;
}
buildObject("{ a:1, b:'hello'}"); // returns {a: 1, b: "hi", undefined: undefined}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment