Search code examples
javascriptloopsnode-red

node-red loop through global variables


Using node-red; I'm storing data in global variables. I'm using a guid as the identifier for the variable. e.g:

global.set(msg.guid,{"watch":true, "command":msg.content, "custno":msg.custno, "result":msg.payload});
return msg;

In a separate flow I want to loop through all these variables to check the content and act accordingly. I can't find a way to get to the global variables apart from:

global.get("theguid");

So I have to know all the guids, and I don't know the number of items.

I have some thoughts on how to approach this, but wondered if I'm missing something obvious!

Thanks for reading


Solution

  • One approach is to use a single top-level context object, rather than scatter your objects in the global namespace.

    For example:

    var myObjects = global.get("myObjects");
    myObjects[msg.guid] = {"watch":true, "command":msg.content, "custno":msg.custno, "result":msg.payload};
    global.set("myObjects",myObjects);
    return msg;
    

    You can then retrieve the myObjects object and use all the standard JavaScript functions for working with it:

    var myObjects = global.get("myObjects");
    var listOfGuids = Object.keys(myObject);
    // etc