如果字符串包含键则返回一个值
我有一个包含警报名称作为键的JS对象(LogGroupMap),其日志组作为值。警报名称以不同长度的一致名称传递,但每次都会在结尾处生成字符,因此我试图查看字符串是否包含logGroupmap对象的键,如果这样,我想获得关联的值用那个钥匙。
let logGroup = (alarmName) => {
Object.keys(logGroupMap).forEach((key) => {
if (alarmName.includes(key)) { logGroup = logGroupMap.key; }
});
};
console.log(logGroup(messageDetails.AlarmName));
目前,在所有情况下,这都是不确定的。
I have a JS Object Literal (logGroupMap) containing alarm names as keys, and their log groups as values. Alarm names are passed in with consistent names of varying length but with generated characters at the end each time, so I'm trying to see if the string includes a key from the logGroupMap object literal, and if so I want to get the value associated with that key.
let logGroup = (alarmName) => {
Object.keys(logGroupMap).forEach((key) => {
if (alarmName.includes(key)) { logGroup = logGroupMap.key; }
});
};
console.log(logGroup(messageDetails.AlarmName));
Currently this is returning undefined in all cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 Array.find() 方法搜索匹配的键。
要动态访问属性,请使用
logGroupMap[key]
。logGroupMap.key
返回名为key
的属性的值,它不使用key
作为变量。Use the
Array.find()
method to search for a matching key.To access a property dynamically, use
logGroupMap[key]
.logGroupMap.key
returns the value of the property namedkey
, it doesn't usekey
as a variable.