2

I have two JS objects, I want to check if the first Object has all the second Object's keys and do something, otherwise, throw an exception. What's the best way to do it?

function(obj1, obj2){
    if(obj1.HasAllKeys(obj2)) {
         //do something
    }
    else{
         throw new Error(...);
    } 
};

For example in below example since FirstObject has all the SecondObject's key it should run the code :

FirstObject
{
    a : '....',
    b : '...',
    c : '...',
    d : '...'
}
SecondObject
{    
    b : '...',    
    d : '...'
}

But in below example I want to throw an exception since XXX doesnt exist in FirstObject:

FirstObject
{
    a : '....',
    b : '...',
    c : '...',
    d : '...'
}
SecondObject
{    
    b : '...',    
    XXX : '...'
}

4 Answers 4

5

You can use:

var hasAll = Object.keys(obj1).every(function(key) {
  return Object.prototype.hasOwnProperty.call(obj2, key);
});
console.log(hasAll); // true if obj2 has all - but maybe more - keys that obj1 have.

As a "one-liner":

var hasAll = Object.keys(obj1).every(Object.prototype.hasOwnProperty.bind(obj2));
Sign up to request clarification or add additional context in comments.

11 Comments

Any reason to use .call instead of just obj.hasOwnProperty(key)?
Hmm, it seems like creating an object that doesn't inherit from Object is a recipe for disaster....
Yes my friend, or if you override hasOwnProperty yourself.
Although in the latter case, maybe the caller should respect the programmer's replacement. He wanted his object to have custom semantics.
|
5

You can write a function to iterate and check:

function hasAllKeys(requiredObj, secondObj) {
    for (var key in requiredObj) {
        if (!secondObj.hasOwnProperty(key)) {
            return false;
        }
    }

    return true;
}

hasAllKeys(SecondObject, FirstObject);

3 Comments

I want something to be in one line like python :), can we avoid for loop and checking one by one?
Javascript doesn't have list comprehensions, it's harder to make one-liners for things like this.
@Am1rr3zA Even if you don't see the iterations they are still happening, if anything the solution that tymeJV have provided is the fastest.
1

You can use jQuery's $.map method as follows:
$.map(a,function(value, key) {return b[key];}).length != b.length

1 Comment

Using a framework when the original question is clearly looking for plain JavaScript is generally frowned upon (particularly for something as trivial as this), plus, given the typos, you clearly haven't tested it. Answers should either be tested or at least you should mention that you haven't tested it and why.
-1

Another way to do this, that seems to work fine as well.

   const o1 = {
              a : '....',
              b : '...',
              c : '...',
              d : '...'
            },

         o2 = {
             b : '...',
             d : '...',
          };

///////////////////////
///// I. IN ONE LINE
///////////////////////
/**/
/**/  if(Object.keys(o2).every(key =>
/**/       key in o1
/**/       // Object.keys(o1).includes(key)
/**/       // Object.keys(o1).filter(x => x==key).length
/**/  ))
/**/  console.log(true);
/**/  else throw new Error("...");
/**/
///////////////////////


///////////////////////
///// II. IN A FUNCTION
///////////////////////
/**/
/**/    var hasAll = (o1 , o2) => {
/**/      let r = Object.keys(o2).every(key =>
/**/        // Object.keys(o1).includes(key)
/**/        // key in o1
/**/        // Object.keys(o1).filter(x => x==key).length
/**/
/**/         Object.keys(o1)
/**/         .reduce((acc,act,arr) =>
/**/            acc && (key in o1) // , true
/**/         )
/**/
/**/      );
/**/      return r;
/**/    }
/**/
/**/ let cond = hasAll(o1 , o2);
/**/
/**/ console.log(cond);
/**/
/**/ if (cond) console.log(true)
//   /**/ else throw new Error("At least, one key doesn'e exist");
/**/
/**/ ////////
/**/
/**/ cond = hasAll(o2 , o1);
/**/
/**/ console.log(cond);
/**/
/**/ if (cond) console.log(true)
/**/ else throw new Error("At least, one key doesn'e exist");
/**/
///////////////////////

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.