Has Certain Key

Has Certain Key

In nested objects if all of the keys have same key it returns true if some of them do not have it returns false;

Example:
console.log(hasCertainKey(arr,’isCatOwner’)) false
console.log(hasCertainKey(arr,’title’)) true
console.log(hasCertainKey(arr,’first’)) true

function hasCertainKey(arr, key){
  return arr.every(function(val){
    return key in val
  })
}

  var arr = [

        {title: "Instructor", first: 'Elie', last:"Schoppik"}, 

        {title: "Instructor", first: 'Tim', last:"Garcia", isCatOwner: true}, 

        {title: "Instructor", first: 'Matt', last:"Lane"}, 

        {title: "Instructor", first: 'Colt', last:"Steele", isCatOwner: true}

    ]
console.log(hasCertainKey(arr,'isCatOwner')) false
console.log(hasCertainKey(arr,'title')) true
console.log(hasCertainKey(arr,'first')) true


We create a function called hasCertainKey with parameter called arr and key

We return the arr.every every is build in JavaScript method that needs all to be true from the array or not;

Then return key in val The in operator returns true if the specified property is in the specified object or its prototype chain. -MDN



comments powered by Disqus