Object.fromEntries 方法就是 entries 的逆操作,作用是將一個鍵值對陣列轉化為一個物件
同樣的該方法也已經成為 ES10 中 stage4 提案:

Object.entries
在介紹 fromEntries 之前,回顧一下 entries 的用法。這個方法返回的是物件自身的、可列舉的屬性組成的陣列:
const obj = { a: '1', b: 2 }
Object.entries(obj)
複製程式碼

也可以通過 new Map 建構函式將物件轉為 Map:
new Map(Object.entries(obj))
// Map(2) {"a" => "1", "b" => 2}
複製程式碼

Object.fromEntries
fromEntries 方法則剛好相反,將陣列轉為物件:
Object.fromEntries([['a', '1'], ['b', 2]])
複製程式碼

當然也可以傳入一個 Map 將其轉為物件:
const map = new Map().set('a', 1).set('b', 2)
Object.fromEntries(map)
複製程式碼

幾個注意事項
當傳入的引數中有重複出現的 key:
傳入給 fromEntries 的引數,如果有重複的 key 出現,後面的會被採用:
Object.fromEntries([['a', '1'], ['a', '2']])
複製程式碼

雖然 entries 不支援 symbol 作為 key,但 fromEntries 卻可以:
Object.fromEntries([[s, 1]])
Object.entries({ s: 1 })
複製程式碼
上述程式碼效果如下,entreis 接收的物件中如果有 symbol 作為 key 會直接被轉換為字串:

key 為字串或 symbol 之外的型別會被強制轉為字串:

他可以接收任何類陣列,如 Map 等,甚至是有自定義迭代器的物件:
obj = {}
obj[Symbol.iterator] = function* () {
yield [1, 11]
yield [2, 22]
yield [3, 33]
}
console.dir(Object.fromEntries(obj))
複製程式碼

最後還有隻支援建立物件可遍歷的屬性
應用:過濾屬性
定義一個函式,這個函式第一個引數為物件,另外接收其他幾個引數作為需要保留的屬性
function foo(obj, ...keys) {
return Object.fromEntries(Object.entries(obj)
.filter(([key]) => keys.includes(key))
)
}
console.table(foo({ name: 'oli', age: '12' }, 'name'))
複製程式碼

應用:處理表單
假設我們有這樣一組資料:
[{
name: 'oli',
age: 12
}, {
name: 'troy',
age: 14
}]
複製程式碼
如果需要將其填充到 csv、sql 資料庫表中,那麼只需要如下方法過濾資料:
arr = [{
name: 'oli',
age: 12
}, {
name: 'troy',
age: 14
}]
obj = Object.fromEntries(
arr.map(({name, age}) => [name, age])
)
console.table(obj)
複製程式碼

資料過濾完畢後就可以很輕鬆的貼上到 Excel 表格或方便的儲存到資料庫中
應用:交換屬性和值
function foo(obj) {
return Object.fromEntries(Object.entries(obj)
.map(([key, value]) => [value, key])
)
}
console.table({ name: 'oli', age: '12' })
console.table(foo({ name: 'oli', age: '12' }))
複製程式碼

還有其他通過使用陣列方法來實現的各種功能,這裡就不一一展示了
應用:將 url 查詢字串轉為物件
query = Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
// {foo: "bar", baz: "qux"}
複製程式碼

測試環境
想要嘗試的童鞋,需要下載 chrome 測試版,保證 chrome 瀏覽器版本要大於 73:

參考:
- https://www.chromestatus.com/features/5747878282657792
- https://github.com/tc39/proposal-object-from-entries
- http://2ality.com/2019/01/object-from-entries.html
更多內容關注:
