Extracting data from a msg object with a number in it's name

I'm trying process data coming from the OpenWeatherMap node
but i'm stuck on one parameter that has a number in it's name and the template complains about formatting.

So I want to check if msg.data.snow exists in the message and if it does I want to extract msg.data.snow.1h

I tried with hasOwnProperty("snow") but to me it seems like it works only with msg.payload.
And I can't use var placeholder = msg.data.snow.1h; for getting the value

Thank you

You can use the built-in tools to save you having to figure this out but the answer is you use square brackets notation.

The tools...

There’s a great page in the docs (Working with messages : Node-RED) that will explain how to use the debug panel to find the right path to any data item.

Pay particular attention to the part about the buttons that appear under your mouse pointer when you over hover a debug message property in the sidebar.


let placeholder = msg.data.snow["1h"];

Thank you both!
You learn something every day :slight_smile:

So it seems I still have errors. It works but it thows errors.

My node

if (msg.data.hasOwnProperty("snow") == true){
    flow.set("SnowStore", msg.data.snow["1h"]);
    if(msg.topic == ""){
        flow.set("SnowStore", '0');

Example data:

{"coord":{"lon":99.9999,"lat":99.9999},"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10n"}],"base":"stations","main":{"temp":275.45,"feels_like":275.45,"temp_min":272.53,"temp_max":283.48,"pressure":1000,"humidity":100,"sea_level":1000,"grnd_level":937},"visibility":298,"wind":{"speed":0.82,"deg":300,"gust":1.22},"rain":{"1h":1.63},"clouds":{"all":100},"dt":1670611004,"sys":{"type":2,"id":2010780,"country":"AA","sunrise":1670567697,"sunset":1670599008},"timezone":9900,"id":9999999,"name":"NameOfTown","cod":999}

Here the snow object is missing and the debug window thows an error

TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')

If msg.data is not an object you will get this error.

You have multiple options by probably this is what you want...

if (msg.data && msg.data.snow){
    flow.set("SnowStore", msg.data.snow["1h"]);
} else if(msg.topic == ""){
    flow.set("SnowStore", '0');

... or even shorter:

if (msg.data?.snow){
1 Like

It works! Thank you
how come data isn't an object? It says object in the debug window?

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