Sunday, April 15, 2012

Javascript - Object.keys Browser Compatibility

For Object.keys compatibility in all browsers add this code before using Object.keys.

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

You can now use Object.keys as normal such as Object.keys(myObject).length

Post a Comment