0

I am trying to modifying a message payload in node-red by adding a new field coming from the global.context. For example given the as input the following message.payload

{"field1" : 5}

and assuming the global context has a field {"lot" : {"f1" : 4, "f2" : 4}}

I want as output:

{
  "field1" : 5,
  "lot" : {"f1" : 4, "f2" : 4}
}

I would like to do it without using the function palette. As far as I understand this must be done with the change setting move global.context to msg.payload overwrites completely the message so that it results in final message payload being

{"lot" : {"f1" : 4, "f2" : 4}}

How is a new field-value pair added to the message payload?

roschach
  • 8,390
  • 14
  • 74
  • 124

1 Answers1

1

You are close to a solution... but instead of overwriting the entire msg.payload object, use a change node configured to "Set" msg.payload.lot - to - global.lot (or whatever the name of the global variable is).

This should create the new "lot" property inside the msg.payload object -- but beware that this will only work if msg.payload is already an object. Trying to add a new property to a string or number payload will have no effect, since JavaScript treats that as a noop.

SteveR
  • 1,015
  • 8
  • 12
  • Thank you: maybe I have understood. But I need a further step: suppose I want to modify the global context adding a new field using data coming from an http request. Is it possible to do that? – roschach Jul 20 '18 at 08:40
  • Sure -- wire the `http in` node to a change node that sets `global.`**lot** to some value passed into the request (use a `debug` node set to show the full msg object and copy the "path" to the value -- then use that path in your change node). – SteveR Jul 20 '18 at 13:12
  • Sorry what I meant is that both the field name and the data come from the http request. For example I have `global.context.lot.cams` which is supposed to be an array such as `{"id0" :{ ...}, "id1" : {...} }`. Now I built from the request a new object but the field name comes from http parameter. So in the `change` node I would have to do something like `Set` `global.context.lot.cam.[idComingFromHTTPRequest]` to the object value I built. – roschach Jul 20 '18 at 14:10