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 are 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.

--

--

--

Full-Stack Software Developer

Recommended from Medium

What are Primitive and Reference Types in JavaScript?

5 Questions for Building a Monorepo

How To Update Array State In React Hook

knapsack problem in Dynamic programming

Frontend Digest #2 (April 2020)

Javascript-3 ImportantObject’s Properties.

You never knew your Mac could do this. Helpful automation, quick and easy.

Typescript Generic Function Splat

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Bravo

Gabriel Bravo

Full-Stack Software Developer

More from Medium

A long and boring article about how to set up JWT in a Node application

Setting up eslint, prettier, airbnb-base and typescript

JSON Modules in JavaScript | Load JSON file easily without Fetch API

Map, reduce and filter examples in javascript