Reputation: 9376
In nodered I want to add a JSON object to an array stored in a global context object.
The global context is initialized as
{
"lot":
{
"total":0,
"free":0,
"occupied":0,
"cams":[]
}
}
When an HTTP request happens I need to add an object to the global context cams
.
I try to do this using a change
node with Set
context.lot.cams
to the following JSONATA:
$append(global.context.lot.cams,
{$string(msg.req.params.cam) :
{"total" : msg.req.body.totalLots,
"free" : msg.req.body.totalLots - msg.req.body.occupied,
"occupied" : msg.req.body.occupied}
}
)
However instead of appending it overwrites the cams
array with the new element.
How to append a custom object built using http request parameters to a global context array in node-red?
Upvotes: 0
Views: 352
Reputation: 10117
The easiest way to do this would be a Function node. Based on what you've shared, something along the lines of the following would do it:
var myData = global.get("context.lot.cams");
var newObj = {};
newObj[msg.req.params.cam] = {
"total" : msg.req.body.totalLots,
"free" : msg.req.body.totalLots - msg.req.body.occupied,
"occupied" : msg.req.body.occupied
};
myData.push(newObj);
global.set("context.lot.cams",newObj);
return msg;
Upvotes: 1