Convert a String representation of a JavaScript Object to an Object

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 …

~

Did this help you out? Like what you see?
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!

BuymeaCoffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.