[perf] “keys” or “hasOwnProperty” in for in loops

Normalizes many of the for in calls we have
to use Object.keys(or a polyfill) to loop
through the object instead of for in (which
is slower). Also handles cases where
hasOwnProperty could get called on an object
with a null prototype.

fixes github #5607