json-logic-js icon indicating copy to clipboard operation
json-logic-js copied to clipboard

use the data "var" in side "filter"

Open ghost opened this issue 7 years ago • 3 comments

Does anyone know how do I pass in the data by using "var" inside "filter"? because the "var" inside filter alw default to the filtering array elements. Eg the rules and data as below:

Rules:

{ "filter": [ [ { "min": 1, "max": 1, "value": "a" }, { "min": 2, "max": 2, "value": "b" } ], {"<=":[{"var":"min"},{"var": "input"},{"var": "max"}]} ] }

Data:

{input: 1}

ghost avatar Oct 29 '18 14:10 ghost

This seems impossible. Did you find proper workaround?

char-m avatar Oct 10 '19 19:10 char-m

When calling your function on the elements of the array, your context is only that array element. Essentially, there's no lambda capture.

ubik2 avatar Nov 23 '22 10:11 ubik2

Newer to this library but best way I have found to make this work is to define an additional operator that creates an array with the data as context, so that you can access it within map/filter/etc by making a var lookup into "context" (and can still look up the array element via "elem").

jsonLogic.add_operation('arrayWithContext', function (array) {
  const context = this;
  return array.map(elem => ({ elem, context }));
});

pthun avatar Oct 09 '23 15:10 pthun