Create Objects from List object (global context)

Trying to create a list of Mixers objects in the Global Context and set the MixerID property as defined in List object. Objects are defined as:

//Mixer Object definition
    var MixerUDT = {
                    "MixerID" : "",
                     "Speed_SP":0, 
                     "Speed_PV":0, 
                     "Direction":0, 
                     "Comms_OK":1, 
                     "Comms_Sent_ID":0,
                     "Comms_Retires":0,
                     "Comms_Errors" :0 
                     }


    //List of Mixer to create including their ID
    var MixerList = {
                     "M01": "Mixer01",
                     "M02": "Mixer02" 
                     }

Looking for help with code to iterate through MixerList to create mixers M01 & M02 and set their MixerIDs to "Mixer01" and "Mixer02" respectively...Alternatively, help debugging any one of the approaches I've tried below:

All approaches I've tried create Mixers object with correct names, but the MixerID for all mixers is the same: "Mixer02". Cannot for the life of me work out why.
Suspect it has something to do with not understanding when pass-by-references versus pass-by-value is occurring!

APPROACH 1:

//For each Key in  MixerList create a MixerUDT and set MixerID
    for ( let KeyName in MixerList) {
        MixerUDT.MixerID = MixerList[KeyName];   //set MixerID in UDT 
        global.set(KeyName.toString(),MixerUDT); //create instance in global context

        //For Diagnostics
        msg.payload = MixerUDT;         //In each iteration I see MixerUDT has been correctly updated
        node.send(msg);
    }


APPROACH 2:

 //For each Key in  MixerList create a MixerUDT and set MixerID
    for ( let KeyName in MixerList) {
        global.set(KeyName.toString(),MixerUDT);   //create instance of default UDT

        let _Mixer = global.get(KeyName.toString()); //get reference to global variable?!
        _Mixer["MixerID"] = MixerList[KeyName];      //change the MixerID

        //For Diagnostics
        msg.payload = _Mixer;         //In each iteration I see _Mixer has been correct updated
        node.send(msg);
        }

Thanks in advance.

You are setting references to the same object each time. You need to clone it.

Try

const clone= {...MixerUDT}
clone.name = KeyName
global.set(KeyName.toString(), clone)
1 Like

Thanks for helping out a NOOB, Steve.

Is the line const clone= {...MixerUDT} pseudo code?!
I'm not familiar with "{..."

Also, I should use:

clone.MixerID = KeyName;

No. This is JavaScript. The ... is the spread (or rest) operator. It works on arrays and objects.

If you need to debug you can use node.warn for point in time values.

E.g.

node.warn({clone})

This will output to the node-red debug sidebar

You're a champ. Thank you.

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