Skip to content

Commit b48ce46

Browse files
committed
docs(object): add Object.fromEntries
1 parent 7a15144 commit b48ce46

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

docs/object-methods.md

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -733,9 +733,9 @@ Object.values(42) // []
733733
Object.values(true) // []
734734
```
735735

736-
### Object.entries
736+
### Object.entries()
737737

738-
`Object.entries`方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。
738+
`Object.entries()`方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。
739739

740740
```javascript
741741
const obj = { foo: 'bar', baz: 42 };
@@ -795,3 +795,40 @@ function entries(obj) {
795795
}
796796
```
797797

798+
## Object.fromEntries()
799+
800+
`Object.fromEntries()`方法是`Object.entries()`的逆操作,用于将一个键值对数组转为对象。
801+
802+
```javascript
803+
Object.fromEntries([
804+
['foo', 'bar'],
805+
['baz', 42]
806+
])
807+
// { foo: "bar", baz: 42 }
808+
```
809+
810+
该方法的主要目的,是将键值对的数据结构还原为对象,因此特别适合将 Map 结构转为对象。
811+
812+
```javascript
813+
// 例一
814+
const entries = new Map([
815+
['foo', 'bar'],
816+
['baz', 42]
817+
]);
818+
819+
Object.fromEntries(entries)
820+
// { foo: "bar", baz: 42 }
821+
822+
// 例二
823+
const map = new Map().set('foo', true).set('bar', false);
824+
Object.fromEntries(map)
825+
// { foo: true, bar: false }
826+
```
827+
828+
该方法的一个用处是配合`URLSearchParams`对象,将查询字符串转为对象。
829+
830+
```javascript
831+
Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
832+
// { foo: "bar", baz: "qux" }
833+
```
834+

0 commit comments

Comments
 (0)