Reputation: 442
I have a function that looks like this :
const comparer = (otherArray) => {
return function (current) {
return (
otherArray.filter(function (other) {
return (
other.Random_1== current.Random_1 &&
other.Random_2 ==
current.Random_2
...
);
}).length == 0
);
};
};
I want to make it configurable from a JSON file like this :
{
"matchingRules": {
"rule_1" : "other.Random_1 == current.Random_1",
"rule_2" : "other.Random_2 == current.Random_2",
...
}
}
And replace the hardcoded rules in the function with the data from the JSON file. How can I make something like this work ?
Upvotes: 0
Views: 152
Reputation: 1932
As @ilkerkaran points out, you could use eval()
to execute snippets of Javascript dynamically loaded from JSON, but that would introduce a large security risk into your code: those snippets could do anything!
It would be safer if you can constrain the structure of your JSON, to only allow certain types of test:
{
"matchingRules": {
"rule_1" : {
"field_1": "Random_1",
"field_2": "Random_1",
"test": "=="
},
"rule_2" : {
"field_1": "Random_2",
"field_2": "Random_2",
"test": ">"
},
...
}
}
While that would make your comparison function slightly more complicated to implement, it means that you can test whether field_1
and field_2
are actually valid properties of current
and other
, do any necessary conversion from string to other types, check their values are valid, and check whether test
is a valid comparison for your application. Obviously you don't have to implement the test
part if you're only interested in testing for equality.
Upvotes: 1
Reputation: 19986
Try using eval
function
const matchingRules = {
"rule_1": "other.Random_1 == current.Random_1",
"rule_2": "other.Random_2 == current.Random_2",
}
const other = {
Random_1: 10,
Random_2: 20
}
const current = {
Random_1: 10,
Random_2: 200
}
console.log(eval(matchingRules.rule_1));
console.log(eval(matchingRules.rule_2));
Upvotes: 0
Reputation: 3140
You can use something like this
const identifiers = {
"rules": {
"Random_1": "Random_1",
"Random_2": "Random_2",
}
}
const comparer = (otherArray) => {
return function (current) {
return (
otherArray.filter(function (other) {
const entries = Object.entries(identifiers.rules);
const conditions = entries.map((k, v) => (
k == v
));
return conditions.indexOf(false) === -1;
}).length == 0
);
};
};
Upvotes: 1