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.
var botwts={"98B17616F9EFA270B92602BD4AFAD1FA36BB53304A07589536F58CF85B4AC423":true,"7C887696418A36A1F6695280CF1D1E07710751D4A3DF9A4B04B0175FA1F1EE05":true,"B398E318FF11163E8372E0279EB567AF03DB4A10EFABE03689355A295CE9254B":true,"abc":true,"9486A4D194C12E0A6CC3B5464534F0C6E4EF10F85E3BDCD402059B73DEA61344":false}
This question can have two meanings
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
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
var v = botwts['abc'] || false;var x = botwts['notthere'] || false;console.log(v,x);// Alternativelyvar x = botwts.hasOwnProperty('abc') ? botwts['abc'] : false;
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