JS:如何将列表项转换为小写并使用它从对象中获取密钥?

问题描述 投票:0回答:1

我有一个列表和一个对象,我想使用列表值来获取其中一个键的值。

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",
        }
    }
}

如您所见,

entities
是小写的,因此在从
temperature
获取值之前,我需要转换为小写。

我尝试了

entities[0].toLowerCase()['unit']
entities[0.toLowerCase()]['unit']
(entities[0].toLowerCase())['unit']
,但我已经没有想法了。

有人知道如何正确执行此操作吗?理想情况下,在一个行中,即无需首先创建具有所有小写值的新列表或字典。如果可能的话,在飞行中:)

javascript json lowercase
1个回答
0
投票

如果此代码存在于全局范围内,则变量“温度”将作为“窗口”对象的属性存在,因此您可以像这样请求它:

window.temperature

或者这个:

window["temperature"]

或者这个:

var entity = "Temperature"
window[entity.toLowerCase()]

所以你的代码可能如下所示:

let entities = ['Temperature', 'Valve', 'Battery', 'Offset']
let temperature = { icon: "mdi:thermometer-bluetooth", unit: "°C" }

msg.topic = window[entities[0].toLowerCase()]['unit']

但是,如果此代码不在全局范围内,例如在函数中,则如果将“温度”变量放入另一个对象中,就会起作用,如下所示:

let entities = ['Temperature', 'Valve', 'Battery', 'Offset']
let stuff = {
  temperature: { icon: "mdi:thermometer-bluetooth", unit: "°C" }
}

msg.topic = stuff[entities[0].toLowerCase()]['unit']

(免责声明:此代码完全未经测试)

© www.soinside.com 2019 - 2024. All rights reserved.