skip to Main Content

I want to check if x, y or z(all string) exists in the Object keys, my longer expression:

if (x in demoObject || y in demoObject || z in demoObject){
 // do the following action
}

Is there a shorter and computationally faster way to do it(if can’t achieve both of them at the same code, I want the solution for each side), if I need to check more than 10 values whether they exist in the object keys?

2

Answers


  1. You could take the prototype function Object.hasOwnProperty and handover the object as thisArg.

    const
        demoObject = { 3: 'hello', 5: 'world' },
        look_for_these = [ 1, 4, 5 ],
        has_key = look_for_these.some(Object.prototype.hasOwnProperty, demoObject);
    
    console.log(has_key);
    Login or Signup to reply.
  2. [x, y, z].every(key => typeof demoObject[key] !== 'undefined')
    

    or in your example

    [x, y, z].every(key => key in demoObject)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search