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?
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!