Object.fromEntries()
Object.fromEntries() 静态方法将键值对列表转换为对象。
¥The Object.fromEntries() static method transforms a list of key-value pairs into an object.
Try it
语法
参数
返回值
描述
¥Description
Object.fromEntries() 方法采用键值对列表并返回一个新对象,其属性由这些条目给出。iterable 参数应该是实现 [Symbol.iterator]() 方法的对象。该方法返回一个迭代器对象,该对象生成两个元素的类似数组的对象。第一个元素是将用作属性键的值,第二个元素是与该属性键关联的值。
¥The Object.fromEntries() method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The iterable argument is expected to be an object that implements an [Symbol.iterator]() method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key.
Object.fromEntries() 执行与 Object.entries() 相反的操作,只不过 Object.entries() 只返回字符串键控属性,而 Object.fromEntries() 还可以创建符号键控属性。
¥Object.fromEntries() performs the reverse of Object.entries(), except that Object.entries() only returns string-keyed properties, while Object.fromEntries() can also create symbol-keyed properties.
注意:与
Array.from()不同,Object.fromEntries()不使用this的值,因此在另一个构造函数上调用它不会创建该类型的对象。¥Note: Unlike
Array.from(),Object.fromEntries()does not use the value ofthis, so calling it on another constructor does not create objects of that type.
示例
将映射转换为对象
将数组转换为对象
对象转换
¥Object transformations
使用 Object.fromEntries、其反向方法 Object.entries() 和 数组操作方法,你可以像这样变换对象:
¥With Object.fromEntries, its reverse method Object.entries(), and array manipulation methods, you are able to transform objects like this:
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 Language Specification # sec-object.fromentries |
浏览器兼容性
BCD tables only load in the browser