I'm trying to discover if an object has some properties and I'm having trouble using the hasOwnProperty method.
I'm using the method on an array (I know the documentation states a string).
The following line returns true:
{ "a": 1, "b": 2 }.hasOwnProperty( ["a"]);
This line returns also true:
{ "a": 1, "b": 2 }.hasOwnProperty( "a", "b");
But this one returns false:
{ "a": 1, "b": 2 }.hasOwnProperty( ["a", "b"])
And I need it to return true. I'm using Object.keys(object) to get the properties that I'm using, and it returns me an array, so I need to use an array on hasOWnProperty.
Is there some theoric concept I'm missing? And is there some way to fix this problems?
The hasOwnProperty() method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty() method can check if an index is available (not empty) in the array.
Both also support ES6 symbols. So what's the difference between the two? The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.
The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it's own.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
There are two things going on here.
First, hasOwnProperty
only takes one argument. So it'll ignore whatever other arguments you pass to it.
Second, (and I'm simplifying slightly here) it's going to convert that first argument to a String, and then check to see if the object has that property.
So let's look at your test cases:
The reason { "a": 1, "b": 2 }.hasOwnProperty( "a", "b");
returns true
is because it's ignoring the second argument. So really it's just checking for "a".
{ "a": 1, "b": 2 }.hasOwnProperty( ["a", "b"])
returns false
because the first argument, ["a", "b"]
, gets converted to "a,b"
, and there's no { "a": 1, "b": 2 }["a,b"]
.
To find out if a given object has all the properties in an array, you can loop over the array and check each property, like so:
function hasAllProperties(obj, props) {
for (var i = 0; i < props.length; i++) {
if (!obj.hasOwnProperty(props[i]))
return false;
}
return true;
}
Or, if you're feeling fancy, you can use the every
function to do this implicitly:
var props = ["a", "b"];
var obj = { "a": 1, "b": 2 };
var hasAll = props.every(prop => obj.hasOwnProperty(prop));
I hope that helps clarify things. Good luck!
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