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 July 2015.
Object.fromEntries()
静态方法将键值对列表转换为一个对象。
尝试一下
const entries = new Map([
["foo", "bar"],
["baz", 42],
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// Expected output: Object { foo: "bar", baz: 42 }
语法
Object.fromEntries(iterable)
参数
返回值
一个新对象,其属性由可迭代对象的条目给定。
描述
Object.fromEntries()
方法接收一个键值对列表,并返回一个新对象,该对象的属性由这些条目给定。iterable
参数应该是实现了 [Symbol.iterator]()
方法的可迭代对象。该方法返回一个可迭代对象,产生包含两个元素的类数组对象。第一个元素是将用作属性键的值,第二个元素是要与该属性键关联的值。
Object.fromEntries()
是 Object.entries()
的逆操作,只是 Object.entries()
只返回字符串键属性,而 Object.fromEntries()
还可以创建符号键属性。
备注:
与 Array.from()
不同的是,Object.fromEntries()
不使用 this
的值,因此在另一个构造函数上调用它不会创建该类型的对象。
示例
将 Map 转换成对象
将 Array 转换成对象
对象转换
通过 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 }
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-object.fromentries |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fromEntries |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support