Link to home
Create AccountLog in
Avatar of MJ
MJFlag for United States of America

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.
var botwts={"98B17616F9EFA270B92602BD4AFAD1FA36BB53304A07589536F58CF85B4AC423":true,"7C887696418A36A1F6695280CF1D1E07710751D4A3DF9A4B04B0175FA1F1EE05":true,"B398E318FF11163E8372E0279EB567AF03DB4A10EFABE03689355A295CE9254B":true,"abc":true,"9486A4D194C12E0A6CC3B5464534F0C6E4EF10F85E3BDCD402059B73DEA61344":false}

Open in new window


Thanks In Advance!
SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
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

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
var v = botwts['abc'] || false;
var x = botwts['notthere'] || false;
console.log(v,x);
// Alternatively
var x = botwts.hasOwnProperty('abc') ? botwts['abc'] : false;

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
if (botwts.hasOwnProperty('abc')) {
   // do something with the knowledge that the key exists even if it is false
}
else {
  // key does not exist
}

Open in new window

Avatar of MJ

ASKER

Any issue with this approach ( x = actionHash)? My main concern is speed and efficiency here.
var keyVal = (typeof botwts == "undefined") ? false : botwts[actionHash] || false;

Open in new window


Thanks!
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of MJ

ASKER

Thank you all!