这篇翻译不完整。请帮忙从英语翻译这篇文章

方法 Object.fromEntries() 把键值对列表转换为一个对象。

{{EmbedInteractiveExample("pages/js/object-fromentries.html")}}

语法

Object.fromEntries(iterable);

参数

iterable
类似实现了可迭代协议 Array 或者 Map 或者其它对象的可迭代对象。

返回值

一个包含提供的可迭代对象条目的对应属性的新对象。

描述

Object.fromEntries() 函数传入一个键值对的列表,并返回一个带有这些键值对的新对象。The iterable argument is expected to be an object that implements an @@iterator method, that returns an iterator object, that produces a two element array-like object, whose first element is a value that will be used as a property key, and whose second element is the value to associate with that property key.

Object.fromEntries()Object.entries 的反转。

示例

 Map 转化为 Object

通过 Object.fromEntries, 可以将 Map 转化为 Object:

const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }

Array 转化为 Object

通过 Object.fromEntries, 可以将 Array 转化为 Object:

const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }

对象转换

 Object.fromEntries 是 Object.entries() 的反转函数, 借用 array manipulation methods 可以转换对象,如下:

const object1 = { a: 1, b: 2, c: 3 };

const object2 = Object.fromEntries(
  Object.entries(object1)
  .map(([ key, val ]) => [ key, val * 2 ])
);

console.log(object2);
// { a: 2, b: 4, c: 6 }

规范

Specification Status
https://tc39.github.io/proposal-object-from-entries Stage 3

浏览器兼容

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
Basic supportChrome No support NoEdge No support NoFirefox Full support 63IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android Full support 63Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No

Legend

Full support  
Full support
No support  
No support

相关链接

文档标签和贡献者

此页面的贡献者: kohai, sunline.bucket
最后编辑者: kohai,