Object.fromEntries()
方法把键值对列表转换为一个对象。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
语法
Object.fromEntries(iterable);
参数
返回值
一个由该迭代对象条目提供对应属性的新对象。
描述
Object.fromEntries()
方法接收一个键值对的列表参数,并返回一个带有这些键值对的新对象。这个迭代参数应该是一个能够实现@iterator方法的的对象,返回一个迭代器对象。它生成一个具有两个元素的类数组的对象,第一个元素是将用作属性键的值,第二个元素是与该属性键关联的值。
Object.fromEntries()
是 Object.entries
的反转。
示例
Map
转化为 Object
通过 Object.fromEntries
, 可以将 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
, 可以将 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()
的反转函数, 借用 数组处理函数 可以转换对象,如下:
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 }
规范
规范 | 状态 | 备注 |
---|---|---|
ECMAScript Latest Draft (ECMA-262) Object.fromEntries |
Draft | 在 ECMAScript 2019 中首次被定义。 |
浏览器兼容
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fromEntries |
Chrome Full support 73 | Edge No support No | Firefox Full support 63 | IE No support No | Opera Full support 60 | Safari Full support 12.1 | WebView Android Full support 73 | Chrome Android Full support 73 | Firefox Android Full support 63 | Opera Android No support No | Safari iOS Full support 12.2 | Samsung Internet Android No support No | nodejs Full support 12.0.0 |
Legend
- Full support
- Full support
- No support
- No support