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" : "",
                     "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!


//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


 //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

Thanks in advance.

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


const clone= {...MixerUDT} = 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.



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.