How to aggregate multiple sub msg objects as one

Trying to write a function without much success:
How to take a msg objects and sub objects and pass them as top msg.
Example:
msg has 3 objects (payload,req,res) and their sub objects.
2 object that generated as part of the http in node [res,req]
single msg.payload contains the following { "color":"red", "size":42 }.

I wish to take the objects from the payload and move them up to the top level where the payload exist beside the res,req. and pass that newly crafted msg to the next node.

Hope that make sense.
Screenshot 2022-12-10 004116

Hi @xHUNx, welcome to the forum.

You just need a Change node like this

This will give you msg.color and msg.size. msg.payload will be empty.

I don't think it's going to work as the payload content is dynamic (constantly changing based on the API body that was submitted) and it's not constant color or size, it could be "move":"up" or "temperature":29

You can iterate through the elements of msg.payload in a function node like this

for (const key in msg.payload) {
   node.warn("Key " + key + " Value " + msg.payload[key])
}

The square brackets notation is needed becaue "msg.payload.key" would be interpreted as the literal name of an element of msg.payload.

A neat way copy all the properties of the payload up to the message is

Object.keys(msg.payload).forEach(key => {
    msg[key] = msg.payload[key]})
return msg;

Nice. You might add

delete msg.payload[key]

If necessary, yes. I did say that my code copied the values. If a move is necessary then they can be deleted from the payload as you suggest. Very likely it is not necessary though.

indeed thanks all for help, I also added to delete the whole payload item as it's not needed there to be empty

Object.keys(msg.payload).forEach(key => {
    msg[key] = msg.payload[key]
    delete msg.payload[key]
})
delete msg.payload
return msg;

If you have delete msg.payload then you don't need the delete msg.payload[key]. Are you sure you need to do that though? What is the benefit? If you do not need to do it then you are just adding lines of code and using up processor time for no purpose.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.