此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Object.fromEntries()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2020年1月.
Object.fromEntries() 静态方法将键值对列表转换为一个对象。
In this article
尝试一下
const entries = new Map([ ["foo", "bar"], ["baz", 42],]);const obj = Object.fromEntries(entries);console.log(obj);// Expected output: Object { foo: "bar", baz: 42 }语法
js
Object.fromEntries(iterable)参数
返回值
一个新对象,其属性由可迭代对象的条目给定。
描述
Object.fromEntries() 方法接收一个键值对列表,并返回一个新对象,该对象的属性由这些条目给定。iterable 参数应该是实现了[Symbol.iterator]() 方法的可迭代对象。该方法返回一个可迭代对象,产生包含两个元素的类数组对象。第一个元素是将用作属性键的值,第二个元素是要与该属性键关联的值。
Object.fromEntries() 是Object.entries() 的逆操作,只是Object.entries() 只返回字符串键属性,而Object.fromEntries() 还可以创建符号键属性。
备注:与Array.from() 不同的是,Object.fromEntries() 不使用this 的值,因此在另一个构造函数上调用它不会创建该类型的对象。
示例
>将 Map 转换成对象
通过Object.fromEntries,你可以将Map 转换成Object:
js
const map = new Map([ ["foo", "bar"], ["baz", 42],]);const obj = Object.fromEntries(map);console.log(obj); // { foo: "bar", baz: 42 }将 Array 转换成对象
通过Object.fromEntries,你可以将Array 转换成Object:
js
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() 和数组操作方法,你可以像这样转换对象:
js
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 |
|---|
| ECMAScript® 2026 Language Specification> # sec-object.fromentries> |