Reading Object in loop

Hi

I'm trying to read every line in a object through a loop function. The object looks like this.
Object

So i tried the following code (also tried with '1'), and to read it directly msg.payload.1 doesn't works because it expexted a string and not a number:
Object read 1

I pretty new in javascript but i thought the $ meant that the word after have to read as a variable. Or i'm i wrong? Because i also tried with a object with words instead of numbers but still doesn't works.

Object read one

Thanks at advance!
Kind regards,
Ward

Try msg.payload['1']

@UnborN thanks for the reply!
I't doesn't work either it says.
' Expected an assignment or function call and instead saw an expression'.

Isn't meant for an array?
So i search for a way to change my object in a array and found the following:
msg.entries = Object.entries(msg.payload);
msg.values = Object.values(msg.payload);
msg.keys = Object.keys(msg.payload);

And with this i can do what i first wanted to do.

But if there is a easy way i can select the line without converting my object to an array please let me know.

Kind regards,
Ward

Those Object commands come in handy when you are looping but i didnt see any loops in your fuctions above.

Test flow :

[{"id":"fad7142c.8cf118","type":"inject","z":"a311c276.8fe21","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"1\":false,\"2\":true,\"3\":false}","payloadType":"json","x":430,"y":1700,"wires":[["211e4649.64d8a2","fb642a73.c1be98"]]},{"id":"211e4649.64d8a2","type":"debug","z":"a311c276.8fe21","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload['1']","targetType":"msg","statusVal":"","statusType":"auto","x":700,"y":1760,"wires":[]},{"id":"fb642a73.c1be98","type":"debug","z":"a311c276.8fe21","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":690,"y":1660,"wires":[]}]

hi @UnborN. My apologies i probably typed something wrong. Because i tried the syntax again and it does works now.

There is indeed no loop in my function yet. I was first trying to read the correct line manually but now i now how it works i can start with the loop.

Thanks for the solution!

Kind regards
Ward

great :wink: .. if you dont have many properties/keys in your object you can read them one by one.

loops are useful and you can do something like :

let values = Object.values(msg.payload);

values.forEach((val,index) => {
 // do something ..
})

forEach

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