Resolved: Check if object has only the given keys using Lodash or Underscore

Question:

Is there a Lodash or Underscore method which can find if an object has only the given keys of that object. I would like a Lodash or Underscore implementation even though this sounds trivial using native JS.
For example if my object looks like and assuming there is a lodash method named hasOnly
const obj = {
    name: undefined,
  age: 15,
  school: 'Some school'
}

_.hasOnly(obj,['name','age']) //return false

_.hasOnly(obj,['name','age','city']) //return false

_.hasOnly(obj,['name','age','school']) //return true
I couldn’t seem to find a way in the docs

Answer:

Quick and dirty:
hasOnly = (obj, props) => _.isEqual(_.keys(obj).sort(), props.sort())
The sorting is done because we are comparing arrays.
As an alternative, one could turn both props and _.keys(obj) into objects where the props and _.keys(obj) are the keys, whereas the value is a dummy one, always the same, such as 1. The function to do so could be something like this:
make1ValuedObj = keys => _.zipObject(keys, Array(keys.length).fill(1))
Then one would pass those to _.isEqual without having to sort anything:
hasOnly = (obj, props) => _.isEqual(make1ValuedObj(_.keys(obj)), make1ValuedObj(props))
The reality is that a kind of “sorting” has to happen when you construct the objects, so I don’t think there’s a real advantage over the solution above.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com