check if key values exists inside array of objects js code example

Example 1: how to check if an element exists in an array of objects js

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

Example 2: how to check if a key exists in an object javascript

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

Example 3: check if a key exists in an object javascript

"key" in obj // true, regardless of the actual value