How do I check if a particular key exists in a JavaScript object or array?
If a key doesn't exist, and I try to access it, will it return false? Or throw an error?
New awesome solution with JavaScript Destructuring:
let obj = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
};
let {key1, key2, key3, key4} = obj;
// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined
// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present
A fast and easy solution is to convert your object to json then you will be able to do this easy task:
const allowed = {
'/login' : '',
'/register': '',
'/resetpsw': ''
};
console.log('/login' in allowed); //returns true
If you use an array the object key will be converted to integers ex 0,1,2,3 etc. therefore, it will always be false
property.key = property.key || 'some default value', just in case I want that key to exist with some value to it