-
-
Save luisalcarasr/7d3647bdb9464ae44d3445ff79d71027 to your computer and use it in GitHub Desktop.
Deep JSON.parse
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
/** | |
* Converts numbers or booleans that are in text string format to native types. | |
* @autor Luis Alcaras <[email protected]> | |
* @version 1.0.2 | |
* @param {Object|Array|Number|String|Boolean} objectOrArray Element to be converted. | |
* @return {Object|Array|Number|String|Boolean} | |
*/ | |
function parse(objectOrArray) { | |
if (Array.isArray(objectOrArray)) { | |
return objectOrArray.map(parse); | |
} else { | |
const numberRegEx = /^[-]?([1-9]{1}[0-9]{0,}(\.[0-9]*)?|0(\.[0-9]*)?|\.[0-9]*)$/; | |
let object = objectOrArray; | |
if(numberRegEx.test(object)) { | |
object = Number.parseFloat(object); | |
} else { | |
if (typeof object === 'object') { | |
for (const key in object) { | |
object[key] = parse(object[key]); | |
} | |
} | |
} | |
return object; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment