Skip to content

Instantly share code, notes, and snippets.

@dutchcelt
Created October 31, 2014 08:08
Show Gist options
  • Select an option

  • Save dutchcelt/5ce759ba91b9b2d5badb to your computer and use it in GitHub Desktop.

Select an option

Save dutchcelt/5ce759ba91b9b2d5badb to your computer and use it in GitHub Desktop.
Convert a string to an object and add its value
/**
* Convert a string to an object and add its value
* "formItem.address" -> {"formItem":{"address":"address value"}}
* @param {string} dotNotationString - A string that contains dots that whould map to an object key.
* @param {string} val - Value to be added to the key
*/
var dotNotationStringToObject = function( dotNotationString, val ){
var str = "{";
var strEnd = "}";
var obj = {};
var stringArray = dotNotationString.split(/\./);
if( dotNotationString.indexOf(".") === -1 ){
obj[dotNotationString] = val;
} else {
while( stringArray.length > 1) {
str += '"' + stringArray.shift() + '":{';
if( stringArray.length > 1 ) { strEnd += '}'; }
}
str += '"' + stringArray.shift() + '":"' + val + '"}' + strEnd;
obj = JSON.parse( str );
}
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment