Sometimes I run the following on JSON string objects:
for(var i in JSONObject){
....
}
Do I need to run .hasOwnProperty
here? I assume since JSON isn't extended from a parent object, it is safe to assume all its properties are its own.
Sometimes I run the following on JSON string objects:
for(var i in JSONObject){
....
}
Do I need to run .hasOwnProperty
here? I assume since JSON isn't extended from a parent object, it is safe to assume all its properties are its own.
I assume since JSON isn't extended from a parent object, it is safe to assume all its properties are its own.
That's not quite right. Unless an object was created via Object.create(null)
, it has Object.prototype
in its prototype chain. Properties such as hasOwnProperty
, that you mentioned, or toString
are defined there. So, most objects have more than just "their own" properties, that includes objects that have been created from JSON via JSON.parse
.
However, all standard properties defined on Object.prototype
, are not enumerable and hence won't appear in a for..in
loop.
So, should you use hasOwnProperty
? As so often: It depends.
If you are sure that no code that you use, be it your own or third-party code, adds enumerable properties to Object.prototype
, then there is no reason to use hasOwnProperty
in the loop.
If you are not sure about it then you might want to use hasOwnProperty
, but it would be better to simply not extend Object.prototype
with enumerable properties and avoid third-party code that does.
Related:
I ran a couple of tests on this and JSON strings won't transmit inherited properties. So let's say you have an API response from an endpoint that looks like this after you prettify it:
{
"one": "blue",
"two": "watermellon",
"three": "lalal",
"four": "value"
}
If you run a for(var i in JSONObject)
loop over the parsed value of the above, you'll only ever find four properties associated with the object as long as you didn't explicitly attach any properties to the parent Object literal (Object.prototype
) in your current environment.