检查 Object.key() 是否匹配变量

0 javascript for-loop object

我有一个对象:

messages = {
    V1: {
        summary: "summary one",
        cause: "cause one",
        code: "1"
},
    V2: {
        summary: "summary two",
        cause: "cause two,
        code: "2"
}
Run Code Online (Sandbox Code Playgroud)

我想将我的 event.details 的值与对象消息的键进行比较,并为匹配键的摘要、原因和代码设置变量。

到目前为止我的实现:

 if (event.details === Object.keys(messages)) {
    var a = the summary of the matching key;
    var b = the cause of the matching key;
    var c = the code for the matching key;
};
Run Code Online (Sandbox Code Playgroud)

后来我在我的代码中使用这些变量......目前我的结果是:

event.details = "V1"
Object.Keys(messages) = ["V1","V2"]
Run Code Online (Sandbox Code Playgroud)

但这只是给了我一个键数组。我现在想获取匹配键的信息。

如何检查密钥是否与 event.details 匹配?以及如何将变量设置为key的summary、cause和code?

Fel*_*ing 5

只需访问它:var message = messages[event.details]。如果message是一个对象(不是undefined),它就存在,你可以访问message.summary等:

if (message) {
   // message.summary
   // message.cause
   // ...
}
Run Code Online (Sandbox Code Playgroud)