Reputation:
I have an object:
messages = {
V1: {
summary: "summary one",
cause: "cause one",
code: "1"
},
V2: {
summary: "summary two",
cause: "cause two,
code: "2"
}
I want to compare the value of my event.details to the keys of the object messages and set variables for the summary, cause, and code of the matching key.
My implementation so far:
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;
};
Later I use these varibles in my code.... At the moment my result is:
event.details = "V1"
Object.Keys(messages) = ["V1","V2"]
But this just gives me an array of the keys. I want to get the information of the matching key now.
How can I check to see if the key matches the event.details? And how to set the variables to the summary, cause and code of the key?
Upvotes: 0
Views: 7561
Reputation: 147343
As Felix says, you can usually do:
var message = messages[event.details]
quite safely. However, for a general solution (where event.details might return any value), you may want to either check that event.details is an own property, not an inherited one, or make sure messages doesn't have any inherited properties, e.g.
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"
};
Which is a bit clumsy, so it's a good use of a simple extend function that just copies the own properties of one object to another, so:
function extend(toObj, fromObj) {
Object.keys(fromObj).forEach(function(prop) {
toObj[prop] = fromObj[prop];
});
return toObj;
}
Then you can do:
var messages = extend(Object.create(null), {
V1: {summary: "summary one",
cause: "cause one",
code: "1"
},
V2: {summary: "summary two",
cause: "cause two",
code: "2"
}
});
and now you can be sure that messages has no unexpected properties, regardless of the property name. The extend function can include a "deep" flag to do deep copies, but that's a whole other story (and has plenty of questions and answers already).
Upvotes: 0
Reputation: 816232
Just access it: var message = messages[event.details]
. If message
is an object (not undefined
), it exists and you can access message.summary
, etc:
if (message) {
// message.summary
// message.cause
// ...
}
Upvotes: 5