I'm debating between using JavaScript Object.hasOwnProperty(propName)
and lodash _.has(obj, proName)
function to determine if an object has a property.
Which is more efficient for simple cases? For complex cases? For all cases?
Is there a better library that I haven't mentioned?
Thanks!
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isObject() method is used to find whether the given value is an object or not. It returns a Boolean value True if the given value parameter is an object and returns False otherwise.
The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.
get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.
Well the Lodash _.has()
method is just a call to Object.prototype.hasOwnProperty()
after a check for a null argument. The code grabs a reference early on:
var hasOwnProperty = Object.prototype.hasOwnProperty;
and then _.has(object, prop)
looks like
return object != null && hasOwnProperty.call(object, prop);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With