Help with sorting an object

payload: object
MONITOR-PLUG-11: object
NTP: "41"
Int: "12"
Last: "46m"
NTP: "27"
Int: "12"
Last: "14h"
BULB-15: object

Hi All,

As a bit of a learning exercise I decided to write a flow to check state of my Chrony time server.

After much trial and error I have taken the output of an exec node, split on new lines, removed spaces and managed to create an object as above. This is all done in one function node, but I'm stuck on the last bit!

How do I go about soring the above object by the key? names - MONITOR-PLUG-11 etc?

Have spent far too long trying to work this out so no longer fun :wink:


The question is why? For viewing purposes? For iterating?

The truth is a lot more difficult to explain but this stack overflow post does it some justice...

Tbh, I am struggling to think of a good reason to sort keys in an object.

1 Like

As Steve said you would not normally sort an object, but it is possible if you have reason to do so.

let obj = msg.payload;
msg.payload = Object.keys(obj).sort().reduce((r, k) => Object.assign(r, {[k]: obj[k]}), {})
return msg;
1 Like

Many thanks both.

As I mentioned I was really just trying to learn a bit more about manipulating objects etc. Turning a console output to a usable object seemed like a good exercise.

I understand comments about the sort order but I knew it could be done, and it is easier to check in a debug window for missing devices that way.

@Steve-Mcl I actually remember seeing that post among many others, but now I have working code its easier to reverse engineer to understand how things work.

Example here if anyone is interested.

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