Search code examples
jsonnode-red

Adding Fields to JSON in better way Javascript


I'm using Node-Red and the data is passed using JSON objects. All of the data is in msg.payload. I want to add a new property, the TimeStamp, to the object without all of this unnecessary code...It works but I know this is sloppy.

Is there a better way?

var TimeStamp = new Date();

var newMsg = [ ];

newMsg.push({payload: 
                      { TimeStamp:TimeStamp , 
                        Humidity: msg.payload.Humidity,
                        Temperature: msg.payload.Temperature,
                        CO2: msg.payload.CO2,
                        Light: msg.payload.Light

                      }

            });

return newMsg;

Solution

  • You can add the new property to the existing msg object and pass it on.

    msg.payload.TimeStamp = new Date();
    return msg;
    

    This is the better approach as it leaves all other message properties untouched.