damd
damd

Reputation: 6997

Babel support for Object.entries

I'm looking at the stage 3 proposal of Object.values/Object.entries and I'd really like to use it in my current JavaScript project.

However, I can't figure out whether there's any Babel preset which supports it. Since the GitHub repository linked above says it's a stage 3 proposal, I assumed it would be part of babel-preset-stage-3, but it seems not.

Is there any Babel preset (or even plugin?) that lets me use Object.entries today?

Upvotes: 25

Views: 26359

Answers (4)

elfan
elfan

Reputation: 1131

Another alternative solution that I find in the end of 2020, that works for IE11.

npm install --save-dev babel-plugin-transform-es2017-object-entries

and then add to the package.json

"babel": {
    "plugins": [
        "transform-es2017-object-entries"
    ]
}

Upvotes: 0

damd
damd

Reputation: 6997

What I did was install core-js and then just call this at the top of my file:

require('core-js/fn/object/entries');

This made Object.entries available. Credits to @FelixKling.

Update

In core-js@3, the import path has changed:

require('core-js/features/object/entries');

Upvotes: 14

psv
psv

Reputation: 697

Using babel, installing

  1. babel-preset-env
  2. babel-plugin-transform-runtime

gives support for Object.values/Object.entries as well as other *ES20** functionality.

As per recommendation by the modules, configure .babelrc with the following:

{
  "plugins": ["transform-runtime"],
  "presets": ["env"]
}

Upvotes: 33

Randy
Randy

Reputation: 9849

Update:

As noted in the comments, you can improve performance by using the map function instead of reduce.

Please note that the code is case-sensitive (object != Object).

// Object.values

var objectToValuesPolyfill = function(object) {
    return Object
             .keys(object)
             .map(
                  function(key) {
                    return object[key];
                  }
              );
}

Object.values = Object.values || objectToValuesPolyfill;

// Object.entries

var objectToEntriesPolyfill = function(object) {
    return Object
             .keys(object)
             .map(
                  function(key) {
                    return [key, object[key]];
                  }
              );
}

Object.entries = Object.entries || objectToEntriesPolyfill;

Usage:

// es6

Object.values = Object.values || (x => Object.keys(x).map(k => x[k]));
Object.entries = Object.entries || (x => Object.keys(x).map(k => [k, x[k]]));

// es5

Object.values = Object.values || function(x){ 
    return Object.keys(x).map(function(k){ 
        return x[k];
    })
};

Object.entries = Object.values || function(x){ 
    return Object.keys(x).map(function(k){ 
        return [k, x[k]];
    })
};


const a = {
  key: "value",
  bool: true,
  num: 123
}

console.log(
  Object.values(a)
)

console.log(
  Object.entries(a)
)

Upvotes: 6

Related Questions