Use an object with a hyphen in a function

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:

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

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

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

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?

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

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.

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

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

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.

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.