Use an object with a hyphen in a function

#1

Hello all,

I have a problem with a function in node-red. I want to read an object of the instance spotify-premium. The problem is the hyphen in the name.
The path I would like to read is:

spotify-premium.0.player.isPlaying

So I use:

if (spotify-premium.0.player.isPlaying === true) {
    msg.payload = true;
} else {
    msg.payload = false;
}
return msg; 

This doesn't work:

A leading decimal point can be confused with a dot...

So I tried

if (spotify-premium[0].player.isPlaying === true) { ...

But it gives me an error:

"ReferenceError: spotify is not defined (line 2, col 1)"

I also tried

if (spotify-premium[0].player.isPlaying === true) { ...

This gives me

"TypeError: Cannot read property 'isPlaying' of undefined"

Where is my problem? What have I done wrong?
Thanks in forward :slight_smile:

#2

You already know the root cause: hyphen cannot be used in JavaScript identifiers.

Is there any reason that prevents you from using another identifier?

#3

For your own created properties it is just easier to avoid hyphens, but if incoming data is not under your control you have option to use bracket notation
.

spotify-premium.0.player.isPlaying 

["spotify-premium"].0.player.isPlaying
#4

Wouldn't the 0 also be illegal?

["spotify-premium"]["0"].player.isPlaying

Also, not certain how there is a base object with that name?

Surely it's something like
msg["spotify-premium"]["0"].player.isPlaying?

#5

Yeah, keep things simple, dont do this
msg.nastyobject = {"0__foo-bar":{"1|2":{"a:-b":"evil"}}}

#6

If in doubt about how to reference something send it to a debug node then one of the little buttons that appears when you hover over it, when clicked, will copy the path, which you can paste somewhere and look at.

#7

That feature is very useful however I wish it would suffix it with msg. :slight_smile:

#8

Oh and I wish they had tooltips as I never know which is which :thinking:

#9

It doesn't include msg. so the value can be pasted straight into a Change node (or any other TypedInput field).

Decided, on balance, that was more convenient.

#10

I did suspect that but I typically (or rather untypically ) tend to not use the likes of change nodes and more so use function nodes. But I do appreciate why.