可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
Using babel, installing
- babel-preset-es2017
- babel-plugin-transform-runtime
gives support for Object.values/Object.entries as well as other ES2017 functionality.
As per recommendation by the modules, configure .babelrc with the following:
{ "plugins": ["transform-runtime"], "presets": ["es2017"] }
回答2:
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.
回答3:
I've created these methods myself like this:
Object.values = x => Object.keys(x).reduce((y, z) => y.push(x[z]) && y, []); Object.entries = x => Object.keys(x).reduce((y, z) => y.push([z, x[z]]) && y, []);
These return arrays that represent the expected behaviour on JSON-like objects.
Usage:
Object.values = x => Object.keys(x).reduce((y, z) => y.push(x[z]) && y, []); Object.entries = x => Object.keys(x).reduce((y, z) => y.push([z, x[z]]) && y, []); const a = { key: "value", bool: true, num: 123 } console.log( Object.values(a) ) console.log( Object.entries(a) )