Object.entries() alternative for Internet Explorer and ReactJS

Here's a concise polyfill using Array.prototype.reduce in a rather clever way:

if(!Object.entries) 
    Object.entries = function(obj) {
        return Object.keys(obj).reduce(function(arr, key) {
            arr.push([key, obj[key]]);
            return arr;
        }, []);
    }

Nothing necessarily new to the above answer, but just different code to accomplish the same thing.

Hopefully this helps anyone who stumbles upon this.

// Another approach

const entriesPolyFill = (obj) => Object.keys(obj).map(key => [key, obj[key]]);


// Same thing but easier to read

function entriesPolyFill(obj) {
    const keys = Object.keys(obj);

    const keyValuePairs = keys.map(key => {
        const value = obj[key];
        
        return [key, value];
    });
    
    return keyValuePairs;
 };
 
 
// Possible usage if you don't want to alter Object class:
// Ex: Need key-value pairs to iterate over
const entries = (Object.entries ? Object.entries(obj) : entriesPolyFill(obj));

// Then do whatever you want with the Array
// ---> entries.map(), entries.filter(), etc..

// You could also move the whole thing to a function
// and always call the function so you don't have to
// write excess ternary operators in your code:

// -- In a utils file somewhere else...
export function getEntries(obj) {
  return Object.entries ? Object.entries(obj) : Object.keys(obj).map(key => [key, obj[key]]);
}

// Wherever you need to get entries in you project
import { getEntries } from "<path to utils>";

...

const entries = getEntries(obj);

import 'core-js/es7/object';

This works for me.


The usual first item to research when you want to use a newer API in an older browser is whether there is a simple polyfill. And, sure enough there is a pretty simple polyfill for Object.entries() shown on the MDN doc site:

if (!Object.entries)
  Object.entries = function( obj ){
    var ownProps = Object.keys( obj ),
        i = ownProps.length,
        resArray = new Array(i); // preallocate the Array
    while (i--)
      resArray[i] = [ownProps[i], obj[ownProps[i]]];

    return resArray;
  };