Object.fromEntries()

Object.fromEntries() 静态方法将键值对列表转换为对象。

¥The Object.fromEntries() static method transforms a list of key-value pairs into an object.

Try it

语法

¥Syntax

js
Object.fromEntries(iterable)

参数

¥Parameters

iterable

包含对象列表的 iterable,例如 ArrayMap。每个对象应该有两个属性:

0

代表属性键的字符串或 symbol

1

属性价值。

通常,该对象被实现为双元素数组,第一个元素是属性键,第二个元素是属性值。

返回值

¥Return value

一个新对象,其属性由可迭代项给出。

¥A new object whose properties are given by the entries of the iterable.

描述

¥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 of this, so calling it on another constructor does not create objects of that type.

示例

¥Examples

将映射转换为对象

¥Converting a Map to an Object

使用 Object.fromEntries,你可以从 Map 转换为 Object

¥With Object.fromEntries, you can convert from Map to Object:

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

将数组转换为对象

¥Converting an Array to an Object

使用 Object.fromEntries,你可以从 Array 转换为 Object

¥With Object.fromEntries, you can convert from Array to 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 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:

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 Language Specification
# sec-object.fromentries

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看