For my little helper tool that converts a JavaScript Style Object into Custom Properties I had to convert the contents of the textarea — which is a String — to an actual Object. Lacking a native Object.parse()
— something like JSON.parse()
or Array.from()
but for objects — I created my own function:
const createObjectFromString = (str) => {
return eval(`(function () { return ${str}; })()`);
}
createObjectFromString('{ name: "Bramus", }');
// ~> { name: "Bramus" }
The code takes the String representation of the Object as an argument, and uses that to return from a function that is created+executed on the fly (using an IIFE + eval()
).
Unlike other approaches this function requires no JSON syntax and plays nice with nested Objects and Arrays.
🚨 Note that there’s no type-checking at all going on inside the function, so it can be abused when passing user-input directly to it …
~
Thank me with a coffee.
I don\'t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!
To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.