MJ
asked on
Efficient Indexing of JSON Object Key in JavaScript
I'm trying to figure out the most efficient way in javascript to take a value (x) and compare it against the key of the JSON object. If the key exists in the object then obviously it returns the value associated with the key. Also if the key doesn't exist, return false. I'm trying to make this as fast but browser friendly as possible.
Thanks In Advance!
var botwts={"98B17616F9EFA270B92602BD4AFAD1FA36BB53304A07589536F58CF85B4AC423":true,"7C887696418A36A1F6695280CF1D1E07710751D4A3DF9A4B04B0175FA1F1EE05":true,"B398E318FF11163E8372E0279EB567AF03DB4A10EFABE03689355A295CE9254B":true,"abc":true,"9486A4D194C12E0A6CC3B5464534F0C6E4EF10F85E3BDCD402059B73DEA61344":false}
Thanks In Advance!
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Any issue with this approach ( x = actionHash)? My main concern is speed and efficiency here.
Thanks!
var keyVal = (typeof botwts == "undefined") ? false : botwts[actionHash] || false;
Thanks!
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Thank you all!
1. If the value is false or does not exist (also false) it does not matter - set the result to false.
OR
2. You want to know if the key exists - even it if it has a false value
For both you can use the hasOwnProperty() function
There are two ways to get the value or false if the key does not exist. One using hasOwnProperty and the other using the || (OR) operator
Open in new window
If the key does not exist - then the x/y variables will get the value false.
If however you want to know if the key exists then
Open in new window