I have the following JS object:
let obj = {
b: 1,
c: 1,
d: 2
}
I want to write a function that takes an input array and checks whether the fields listed in this array are present in obj
, but I want to have logic in the conditions. So something like
arr = ['b', 'c' || 'd'] (returns true if obj has an entry for `b`, and for either `c` or `d`)
or
arr = ['c' && 'd'] (returns true only if obj has entries for both `c` and `d`)
so in my function I imagine writing a condition like
return arr.forEach(condition => object[condition])
How can I approach this?
3
Answers
You can do something like this:
Write a finction like the checkFields function takes in the object, and a string representing the condition you want to check for example: "a||b" or "a&&b" or "a",
it’s gonna split the string by || and && and check for the conditions and return true/false based on wether the condition istrue or not.
Next the calcResult function will take an array like ["a||b", "a"] and pass each of the items of it to the checkFields function and return true if all of the results are true.
Build up rules programmatically and evaluate them.
This can be extended with any amount of more checks (like if a property has a specific value, if it is a Date object) and operators (like
not
to invert a result):You are going to have to write yourself some sort of rules engine that is able to process logical checks. Below is a basic idea of using objects.