Reading attributes and tags

Two things to consider here before we get to the answer …

  1. Device tags can have multiple values per tag. i.e. In your device config, you can set a tag of “a=b” and another tag of “a=c”, and when querying the device, you will be returned multiple tags with a key of “a”: one for each unique value.
  2. Depending on how the device got onto your payload, the format of your tags could be different.

If you used the Device: Get Node with the “Return tags as an object map instead of an array” checkbox unchecked, or if you queried a device using the “Device: Get” call in the Losant API Node, your tags will be on your payload in a format like the following …

{
    "myDevice": {
        "tags": [
            {
                "key": "a",
                "value": "b"
            },
            {
                "key": "a",
                "value": "c"
            },
            {
                "key": "foo",
                "value": "bar"
            }
        ]
    }
}

So to get the value of the tag with the key foo, you could use the string template {{valueByKey myDevice.tags 'foo' 'key' 'value'}}. This string template will return the first value that it hits, so it would return “b” if you were trying to get the value of the tag a.

If the device got onto your payload through any other method (e.g. the Device: State Trigger, any of the other device triggers, or the Device: Get Node with the object map checkbox checked), the tags will be in a format like the following:

{
    "myDevice": {
        "tags": {
            "a": [ "b", "c" ],
            "foo": [ "bar" ]
        }
    }
}

The value(s) of each tag is always returned as an array, even if there is only one value for the tag.

Here, to get the value of the tag foo, you would use the string template {{myDevice.tags.foo.[0]}}. The 0 here represents the index of the value you would like; for example, if you wanted the second value of the tag a, this string template would be {{myDevice.tags.a.[1]}}.

As for how to do either in JavaScript, I don’t think there’s a good method I can recommend other than running a for loop like you did in your example. We don’t expose any utility belt libraries for use in the Function Node.