I have a list and an object and I would like to use a list value to get one of the keys' values.
let devices = ['001A2208B97D','001A2208C9FA','001A2214ADC8','001A2214A73A','001A2214B86E','001A2214A6DF','001A2214ADBF','001A2208CFD3']
let entities = ['Temperature', 'Valve', 'Battery', 'Offset']
let temperature = { device_class: 'temperature', icon: "hass:thermometer-bluetooth", unit: "°C"}
let valve = { device_class: '', icon: "hass:valve", unit: "%"}
let battery = { device_class: 'battery', icon: "hass:battery-bluetooth", unit: ""}
let offset = { device_class: '', icon: "hass:offset", unit: "°C" }
for (let i = 0; i < devices.length; i++) {
for (let j = 0; j < entities.length; j++) {
msg.payload = {
"icon": temperature['icon'],
"unit_of_measurement": temperature['unit'],
"state_class": "measurement",
}
}
}
As you can see, the entities
is lower case, so before getting the value from temperature
, I need to convert to lower case.
I tried entities[0].toLowerCase()['unit']
and entities[0.toLowerCase()]['unit']
and (entities[0].toLowerCase())['unit']
and I have run out of ideas.
Does anybody know how to do this correctly? Ideally in a one liner, i.e. without first creating a new list or dict with all the lower case value. On the fly if possible :)
If this code exists in the global scope, the variable "temperature" will exist as a property of the "window" object, so you could request it like this:
window.temperature
Or this:
window["temperature"]
Or this:
var entity = "Temperature"
window[entity.toLowerCase()]
So your code might look like this:
let entities = ['Temperature', 'Valve', 'Battery', 'Offset']
let temperature = { icon: "mdi:thermometer-bluetooth", unit: "°C" }
msg.topic = window[entities[0].toLowerCase()]['unit']
But if this code is not in the global scope, such as in a function, it would work if you put the "temperature" variable inside another object, like this:
let entities = ['Temperature', 'Valve', 'Battery', 'Offset']
let stuff = {
temperature: { icon: "mdi:thermometer-bluetooth", unit: "°C" }
}
msg.topic = stuff[entities[0].toLowerCase()]['unit']
(disclaimer: this code is completely untested)