Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object.keys() method alternative for compatibility with IE8

I'm getting in error when testing in IE8 that the Object method is not supported. I'm using Object.keys()

Object.keys(jsoncont).sort(function(a,b){
   return b.localeCompare(a)
 }).forEach(function(key) {
    var val = jsoncont[key];

   /* My code here */
 });
}

Is there a good workaround for this method that is supported by IE8?

like image 370
Mikarma Avatar asked Dec 05 '22 08:12

Mikarma


1 Answers

Mozilla has an explanation of how to polyfill the function in older browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
  Object.keys = (function () {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function (obj) {
      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}
like image 150
Daab Avatar answered May 20 '23 00:05

Daab