Check if object key exists within object
You should use the in
operator
key in object //true
!(key in object) //false
And undefined
can not be used
obj["key"] !== undefined //false, but the key in the object
For more information, please look at Checking if a key exists in a JavaScript object?
The best way to achieve this would be to rely on the fact that the in
operator returns a boolean value that indicates if the key is present in the object.
var o = {k: 0};
console.log('k' in o); //true
But this isin't your only issue, you do not have any lookup object that allows you to check if the key is already present or not. Instead of using an array, use a plain object.
var groups = {};
Then instead of groups.push(...)
, do groups[group_key] = group_details;
Then you can check if the group exist by doing if (group_key in groups) {}
let data = {key: 'John'};
console.log( data.hasOwnProperty('key') );
I have run into this pattern a lot, and what I end up doing is:
if (object[key]) {
//exists
} else {
// Does not exist
}
so I think in your case it will be:
if (groups[group_key]) {
// Exists
} else {
// Does not exist
}