Reputation: 7
This is my JSON object :
var EVENT_ID = {
"Enable Popup Blocker": "Sol_EnablePopupBlocker_IE",
"Disable Script Debug": "Sol_DisableScriptDebugger_IE",
"Clear History": "Sol_ClearHistory_IE",
"Reset Settings": "Reset_InternetExplorer_Settings_SA",
"Profile Issue": "Fix_Outlook_Profile_SA",
"Send Receive": "Fix_Send_Receive_Errors_Outlook_SA",
"Search Issue": "Fix_Search_Outlook_SA"
};
I am trying to access the JSON object value with keys, which has spaces as shown below
var eventID = JSON.stringify(req.body.result.parameters.solution);
var aptEventName = EVENT_ID[eventID];
eventID
value is "Profile Issue"
When I log my aptEventName
variable, it throws values as undefined
. Can anyone please tell me, where I am going wrong?
Upvotes: 0
Views: 795
Reputation: 38532
ONE POSSIBLE CASE: when you again do JSON.stringify()
on a string value this could happen. That's why it throws values as undefined, so don't use unnecessary JSON.stringify()
here
var response = "response"
JSON.stringify(response)
""response""
^^ ^^ see extra quotes here
var result = { "source": "agent", "resolvedQuery": "LPTP-KDUSHYANT", "speech": "", "action": "gethostname", "actionIncomplete": false, "parameters": { "solution": "Profile Issue", "hostname": "LPTP-KDUSHYANT" }}
var eventID = result.parameters.solution;
var EVENT_ID = {
"Enable Popup Blocker": "Sol_EnablePopupBlocker_IE",
"Disable Script Debug": "Sol_DisableScriptDebugger_IE",
"Clear History": "Sol_ClearHistory_IE",
"Reset Settings": "Reset_InternetExplorer_Settings_SA",
"Profile Issue": "Fix_Outlook_Profile_SA",
"Send Receive": "Fix_Send_Receive_Errors_Outlook_SA",
"Search Issue": "Fix_Search_Outlook_SA"
};
var aptEventName = EVENT_ID[eventID];
console.log(aptEventName)
Upvotes: 2
Reputation: 207527
You should not be using stringify, it is taking a string and turning that string into JSON.
var eventID = JSON.stringify(req.body.result.parameters.solution);
when you do this your string is going to be
var eventID = "\"Profile Issue\"";
So of course you have no properties in your object with quotes. So what you need to do is drop the stringify bit and just have to reference the property in your object.
var eventID = req.body.result.parameters.solution;
var aptEventName = EVENT_ID[eventID];
Upvotes: 1
Reputation: 4993
You can get the values using:
EVENT_ID["Clear History"]
I think you have something wroong with the
req.body.result.parameters.solution
.
Upvotes: 0
Reputation: 2237
JSON.stringify
called on a string will return the string in quotes. You should not JSON-encode your key. And as string typecast is implicit when performing object field access you can type it just as:
var eventID = req.body.result.parameters.solution;
var aptEventName = EVENT_ID[eventID];
Upvotes: 1