should-quote
This is a tiny library to detect if a string should be wrapped in quotes to work as an object key.
How to Install
yarn add should-quote
or...
npm install should-quote
How to Use
First you need to import the function as seen below:
import shouldQuote from 'should-quote';
Then you can use it on string literals...
console.log(shouldQuote('foo'));
console.log(shouldQuote('foo bar'));
...or variables with string value.
const key = 'prop.name';
console.log(shouldQuote(key) ? `obj['${key}']` : `obj.${key}`);
The logged output would have been dot notation if camel case were used.
const key = 'propName';
console.log(shouldQuote(key) ? `obj['${key}']` : `obj.${key}`);
It allows unquoted keys if it complies with the lexical grammar.
const key = '\\u0078';
console.log(shouldQuote(key) ? `obj['${key}']` : `obj.${key}`);