Alternatives to eval()

Hi Guys,

I have a need for a dynamic object defined by a msg.topic within an array and put together the following for testing. Both the solutions for using eval() and object definitions using square brackets work.

However, is there a better way to do this? Baring in mind a completely different solution may be better, but I'm still curious about replacements for eval().

Thanks,

var list = { "find": {"me": [ { "in": {"this": "section"} }, {"in": { "this": "room" } } ] } };
var listArray = list.find.me;
var location = "in.this";
var location2a = "in";
var location2b = "this";
var string = "section";

for (i = 0; i < listArray.length; i++) {
    if (listArray[i].in.this == "section") {
        node.warn("found validation");
        //execute something
    }
    
    if (eval("listArray[i]." + location) == string) {
        node.warn("found using msg strings");
        //execute something
    }
    
    if (listArray[i][location2a][location2b] == string) {
        node.warn("alternative found using msg strings");
        //execute something
    }
}

return msg;

Use RED.util.getObjectProperty to get sub properties of an object using a string

var list = { "find": { "me": [{ "in": { "this": "section" } }, { "in": { "this": "room" } }] } };
var listArray = list.find.me;
var location = "in.this";
var location2a = "in";
var location2b = "this";
var string = "section";

for (let i = 0; i < listArray.length; i++) {
    if (listArray[i].in.this == "section") {
        node.warn("found validation");
        //execute something
    }

    if (RED.util.getObjectProperty(listArray[i], location) == string) {
        node.warn("found using msg strings");
        //execute something
    }

    if (listArray[i][location2a][location2b] == string) {
        node.warn("alternative found using msg strings");
        //execute something
    }
}
1 Like

Dude you rock, thank you very much. I also wasn't aware of this util module so that's something to explore.

Generally speaking are there any other alternates to eval()?

If you are using Monaco editor, type RED.util. and you will see all util functions.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.