TomFrost / Jexl

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

Help passing root object to a jexl transform #88

Closed ricardolpd closed 3 years ago

ricardolpd commented 4 years ago

Does jexl support pointing at the root object, and passing the root object to a transform?

Basically i am using jexl to apply many transforms, but i got a requirement to apply a transform into the root object. I built something outside jexl to support this, but i am wondering if this is supported and i dont need to build it.

If it does, how would i represent this?

Apologies if this is the wrong place to ask this.

TomFrost commented 4 years ago

Hi Ricardo! This is the perfect place to ask.

The quick answer is that you can't reference the root today, but you can do this:

// Instead of this:
jexl.eval(expression, context)
// ...do this!
jexl.eval(expression, { ROOT: context, ...context })

Now, the entire context is available to your expression as the variable ROOT.

The better answer: The solution I proposed to #28 is likely also a solution to this problem. @ will refer to the root of the current relative context. So, essentially, you can count on @ referencing the top level context, unless you're inside of an array filter expression -- in that case, @ will refer to the current array element being evaluated.

You may also be interested in #25, depending on how you're using transforms today. That adds top-level functions to the Jexl syntax. This is fully implemented and documented in the functions branch and will be merged and released soon!

ricardolpd commented 4 years ago

Hi Tom,

Thank you for the suggestions, i will have a go at the proposed solution. I actually didnt think of it. i mearly marked the root object as * and executed the transforms in jexl manually. This is surely better.

Also #25 and look pretty neat #28.

Thank you for this 🙏 (shall i close the issue, or do you usually close it)