Last active
October 11, 2018 15:24
-
-
Save shameen/a73527326bd458eba1b9576e75a5f971 to your computer and use it in GitHub Desktop.
JS: Sanitize JSON data to conform to
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
/** Make property names conform to javascript property name rules. | |
* One use case of this is with Kendo UI's Grid, when the column templates are dynamically generated from JSON | |
*/ | |
sanitizeJsonPropertyNames(arr) { | |
let _return = []; | |
for (let i = 0; i < arr.length; i++) { | |
for (var property in arr[i]) { | |
//sanitize any property names | |
let propertyName = property.toString(); | |
propertyName = propertyName.replace(/[\-_]+/g, '_'); | |
propertyName = propertyName.replace(/[^A-Za-z0-9]+/g, ''); | |
if (!propertyName[0].match(/[A-Za-z_]/)) | |
propertyName = '_' + propertyName; | |
_return[i][propertyName] = arr[i][property]; | |
} | |
} | |
return _return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment