How to add an object to the Node-RED msg.payload

jpsstack picture jpsstack · Aug 25, 2018 · Viewed 8.1k times · Source

I need the Accel object as part of the payload object:

  • msg.payload.Accel.x : 1
  • msg.payload.Accel.y : 2
  • msg.payload.Accel.z : 3

How can I add Accel and x,z,y to payload, ideally using the change node?

I tried this already:

msg.payload.Accel['x'] = 1;
return msg;

and got an error:

"TypeError: Cannot set property 'x' of undefined"

Answer

hardillb picture hardillb · Aug 25, 2018

It all depends on what the msg.payload is to start with. If the input to the function node is a string then msg.payload will be a string and you can't just add arbitrary properties to it.

If the input is already an object then it can be extended, but you need to create the intermediate layers in the object before you can add the value. e.g. assuming the following input msg.payload:

{
  foo: 25,
  bar: 'testing'
}

To add Accel.x you would first need to add a Accel key before trying to add a value to Accel.x. With a function node you would do it like this:

msg.payload.Accel = {};
msg.payload.Accel.x = 1;
msg.payload.Accel['y'] = 2;
return msg;

With a change node it would look something like this as the change node will add the empty layers for you:

Change Node Settings