我有一个对象: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相匹配?以及如何将变量设置为密钥的摘要,原因和代码?
2 回答

holdtom
TA贡献1805条经验 获得超10个赞
只是访问它:var message = messages[event.details]
。如果message
是对象(不是undefined
),则它存在且您可以访问message.summary
等:
if (message) { // message.summary // message.cause // ...}

慕森卡
TA贡献1806条经验 获得超8个赞
正如菲利克斯所说,你通常可以这样做:
var message = messages[event.details]
很安全 但是,对于一般解决方案(event.details可能返回任何值),您可能要检查event.details是自己的属性,而不是继承的属性,或者确保消息没有任何继承属性,例如
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"};
这有点笨拙,所以它很好地利用了一个简单的扩展函数,它只是将一个对象的属性复制到另一个对象,所以:
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" }});
现在您可以确定消息没有意外的属性,无论属性名称如何。该扩展功能可以包括“深”标志,以做深拷贝,但是这完全是另外一个故事(并有大量的问题和答案的话)。
添加回答
举报
0/150
提交
取消