I have the following object literal:
{
'key1':
{
id: 'rr323',
d: undefined,
x: 560,
y: 150
},
'key2':
{
id: 'rr231',
d: undefined,
x: 860,
y: 90
}
}
I want to implement an if statement such as below:
if(key DOES NOT exist in object){
//perform certain function
}
I tried the following:
var key = key1;
if(!(key in global_move_obj)){
// function
}
But that always returns true value when it should return false.
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value.
Using hasOwnProperty() function The function hasOwnProperty() will check for the existence of a key in the given object and returns true if the key is present or else it returns false. This function takes the key of the object as the parameter and returns the Boolean result accordingly.
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Use the hasOwnProperty
call:
if (!obj.hasOwnProperty(key)) {
}
You can do it like:
var key = 'key1';
if (!('key1' in obj)) {
....
}
// or
if (!(key in obj)) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With