Javascript: Validate dynamic conditions in a object node

Consider the tree nodes from the image above.

We would like to navigate through the tree and return some data if the node’s conditions is met.

This may be easy when we have static conditions for all nodes(objA == objB for example). But what about dynamic conditions? how can we handle different condition types for each node?.

We may have the following conditions:

NodeA: Object.property > 50
NodeB: Object.property2 === ‘Agree’
NodeC: Object !== undefined
NodeD: Object.property === ‘A’ or Object.property === ‘B’

For this purpose we will use the library ‘json-rules-engine’ (https://www.npmjs.com/package/json-rules-engine)

This library needs the conditions in a especific format:

[{
“fact”: “property or object to evaluate”,
“operator”: “operator to evaluate”,
“value”: “expected value”
}],

So, to evaluate the node’s conditions we need to include the array of conditions in a property , preferably called ‘conditions’.

The first two nodes will be:

Now, to execute the conditions:

First, we need to import Engine, NestedCondition from ‘json-rules-engine’ library.
import { Engine, NestedCondition } from ‘json-rules-engine’;

Second, create a method to execute the conditions and implement the code:
engine.addRule({ conditions: { all: arrayOfConditions }, event: { type: ‘approved’ }});

const engine = new Engine();

engine.run(objectToValidate).then(({ events }) => {
events.map((event) => {
if (event.type !== ‘approved’) result = false;
});
});

where:
arrayOfConditions is the array of conditions we want to evaluate (for a node)
objectToValidate is the object that contains the data to evaluate (in our case the persona object).

Using this library we can evaluate many different conditions for a node.