TomFrost / Jexl

Javascript Expression Language: Powerful context-based expression parser and evaluator
MIT License
559 stars 90 forks source link

Add support for literals as object keys #104

Closed mediawrbb closed 3 years ago

mediawrbb commented 3 years ago

Firstly, thanks for this great library!

I have a requirement for users to be able to remap the context to new a new object. For example:

const context = { a: 1, b: 2, }

They might map to a new object using the JEXL expression:

{ newKey: a, newKey2: b * 2}

However the target object is completely user configurable (it's for a metadata/form system) and so they often use dashes in the key, which JEXL does not support (but Javascript does).

I have added support for literals after an open bracket so that users can write

{ 'new-key': a, 'new-key-2': b * 2}

I have added a test and all existing tests pass.

Thanks in advance!

TomFrost commented 3 years ago

This is so simple and clever, thanks Bill! Totally agreed that this should be supported. Great add.

Merging now, but I have a couple other things I'd like to fit into the next release. If I can't get the full release cut soon, I'll push this out in its own for you.

mediawrbb commented 3 years ago

Thanks for the speedy response - looking forward to the next release!

blenderskool commented 2 years ago

Thanks for this change @mediawrbb, even my project has a similar requirement. @TomFrost any idea when you'll push this change as a release? I know you are working on a significant update alongside your day job so no pressure, but it would be really helpful if this change could be made available as a release :smile: Thanks for this awesome library!

mediawrbb commented 1 year ago

@blenderskool I completely missed your response, but if you want to patch the package in the meantime to add support this feature, the following does this:

diff --git a/node_modules/jexl/dist/parser/states.js b/node_modules/jexl/dist/parser/states.js
index a8a03fb..0eabc9d 100644
--- a/node_modules/jexl/dist/parser/states.js
+++ b/node_modules/jexl/dist/parser/states.js
@@ -93,6 +93,7 @@ exports.states = {
   },
   expectObjKey: {
     tokenTypes: {
+      literal: { toState: 'expectKeyValSep', handler: h.objKey },
       identifier: {
         toState: 'expectKeyValSep',
         handler: h.objKey

Place this in <project root>/patches/jexl+2.3.0.patch in your project, and use this in conjunction with [patch-package](https://www.npmjs.com/package/patch-package