JavaScript中的Object.fromEntries()方法是標準的內置對象,用於將鍵值對列表轉換為對象。此方法返回一個新對象,其屬性由iterable的條目確定
用法:
Object.fromEntries( iterable )
參數:此方法接受單個參數iterable,該參數包含可迭代對象,例如Array或Map或其他實現可迭代協議的對象。
返回值:此方法始終返回一個新對象,該對象的屬性由Iterable的條目提供。
以下示例說明了JavaScript中的Object.fromEntries()方法:
範例1:將Map轉換為對象。
const map1 = new Map([ ['big', 'small'], [1, 0] ]);
const geek = Object.fromEntries(map1);
console.log(geek);
const map2 = new Map(
[['Geek1', 'Intern'],
['stipend', 'Works basis']]
);
const geek1 = Object.fromEntries(map2);
console.log(geek1);
輸出:
Object { 1:0, big:"small" } Object { Geek1:"Intern", stipend:"Works basis" }
範例2:將數組轉換為對象。
const arr1 = [ ['big', 'small'], [1, 0], ['a', 'z' ]];
const geek = Object.fromEntries(arr1);
console.log(geek);
const arr2 = [ ['Geek1', 'Intern'], ['stipend', 'Works basis'] ];
const geek1 = Object.fromEntries(arr2);
console.log(geek1);
輸出:
Object { 1:0, big:"small", a:"z" } Object { Geek1:"Intern", stipend:"Works basis" }
範例3:其他轉換
const params = 'type=Get_the Value&geekno=34&paid=10';
const searchParams = new URLSearchParams(params);
console.log(Object.fromEntries(searchParams));
const object1 = { val1:112, val2:345, val3:76 };
const object2 = Object.fromEntries(
Object.entries(object1)
.map(([ key, val ]) => [ key, val * 3 ])
);
console.log(object2);
輸出:
Object { type:"Get_the Value", geekno:"34", paid:"10" } Object { val1:336, val2:1035, val3:228 }
支持的瀏覽器:下麵列出了Object.fromEntries()方法支持的瀏覽器:
- 穀歌瀏覽器
- Firefox
- IE
- Opera
- Safari
- Edge
相關用法
- Javascript padStart()用法及代碼示例
- Javascript Int8Array from()用法及代碼示例
- Javascript Reflect.get()用法及代碼示例
- Javascript Reflect.has()用法及代碼示例
- Javascript Unit16Array.from()用法及代碼示例
- Javascript handler.get()用法及代碼示例
- Javascript Int16Array from()用法及代碼示例
- Javascript Uint8Array.from()用法及代碼示例
- Javascript hasOwnProperty()用法及代碼示例
- Javascript compile()用法及代碼示例
- Javascript Uint32Array from()用法及代碼示例
- Javascript Array from()用法及代碼示例
- Javascript Array.from()用法及代碼示例
- Javascript handler.has()用法及代碼示例
- Javascript exec()用法及代碼示例
注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 JavaScript | Object.fromEntries() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。