Check if object has a set of properties in javascript

Viewed 21756

Let's say I have an object named a, how could I check that a has a specific list of multiple properties in shorthand, I think it can be done using in logical operator,

Something like this:

var a = {prop1:{},prop2:{},prop3:{}};
if ({1:"prop1",2:"prop2",3:"prop3"} in a)
    console.log("a has these properties:'prop1, prop2 and prop3'");

EDIT

If plain javascript can't help, jQuery will do, but i prefer javascript

EDIT2

Portability is the privilege

6 Answers

Slightly more elegant use of the Object.every() prototype function to include try-catch:

try {
  const required = ['prop1', 'prop2', 'prop3']
  const data = {prop1: 'hello', prop2: 'world', prop3: 'bad'}
  if (!required.every( x => x in data )) throw new Error('missing property')
  console.log('all properties found')
} catch(err) {
  console.log(err.message)
}
``
Related