Checking if a key exists in a JS object
var obj = {
"key1" : "k1",
"key2" : "k2",
"key3" : "k3"
};
if ("key1" in obj)
console.log("has key1 in obj");
=========================================================================
To access a child key of another key
var obj = {
"key1": "k1",
"key2": "k2",
"key3": "k3",
"key4": {
"keyF": "kf"
}
};
if ("keyF" in obj.key4)
console.log("has keyF in obj");
Above answers are good. But this is good too and useful.
!obj['your_key'] // if 'your_key' not in obj the result --> true
It's good for short style of code special in if statements:
if (!obj['your_key']){
// if 'your_key' not exist in obj
console.log('key not in obj');
} else {
// if 'your_key' exist in obj
console.log('key exist in obj');
}
Note: If your key be equal to null or "" your "if" statement will be wrong.
obj = {'a': '', 'b': null, 'd': 'value'}
!obj['a'] // result ---> true
!obj['b'] // result ---> true
!obj['c'] // result ---> true
!obj['d'] // result ---> false
So, best way for checking if a key exists in a obj is:'a' in obj
That's not a jQuery object, it's just an object.
You can use the hasOwnProperty method to check for a key:
if (obj.hasOwnProperty("key1")) {
...
}
Use the in
operator:
testArray = 'key1' in obj;
Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.