Created
October 31, 2014 08:08
-
-
Save dutchcelt/5ce759ba91b9b2d5badb to your computer and use it in GitHub Desktop.
Convert a string to an object and add its value
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
| /** | |
| * 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