【问题标题】:Check if Object.key() matches a variable检查 Object.key() 是否匹配变量
【发布时间】:2016-04-05 04:29:02
【问题描述】:

我有一个对象:

messages = {
    V1: {
        summary: "summary one",
        cause: "cause one",
        code: "1"
},
    V2: {
        summary: "summary two",
        cause: "cause two,
        code: "2"
}

我想将我的 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;
};

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

event.details = "V1"
Object.Keys(messages) = ["V1","V2"]

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

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

【问题讨论】:

  • 因为最后少了一个 "
  • Object.keys 返回一个数组,它是一个对象,所以它永远只会是 === 给它自己。

标签: javascript object for-loop


【解决方案1】:

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

if (message) {
   // message.summary
   // message.cause
   // ...
}

【讨论】:

    【解决方案2】:

    正如菲利克斯所说,您通常可以这样做:

    var message = messages[event.details]
    

    相当安全。但是,对于一般解决方案(其中 event.details 可能返回任何值),您可能需要检查 event.details 是自己的属性,而不是继承的属性,或确保 messages 没有任何继承属性,例如

    var messages = Object.create(null);
    messages['V1'] = {
        summary: "summary one",
        cause: "cause one",
        code: "1"
    };
    messages['V2'] = {
        summary: "summary two",
        cause: "cause two",
        code: "2"
    };
    

    这有点笨拙,所以它很好地使用了一个简单的extend函数,它只是将一个对象的自己的属性复制到另一个对象,所以:

    function extend(toObj, fromObj) {
      Object.keys(fromObj).forEach(function(prop) {
        toObj[prop] = fromObj[prop];
      });
      return toObj;
    }
    

    那么你可以这样做:

    var messages = extend(Object.create(null), {
      V1: {summary: "summary one",
           cause: "cause one",
           code: "1"
      },
      V2: {summary: "summary two",
           cause: "cause two",
           code: "2"
      }
    });
    

    现在您可以确定消息没有意外属性,无论属性名称如何。 extend 函数可以包含一个“deep”标志来进行深度复制,但这是另一回事(并且已经有很多问题和答案了)。

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2011-11-12
      • 2017-09-26
      相关资源
      最近更新 更多