Chuyển đổi cặp key-value thành Object
Object.fromEntries() (ES2019) thực hiện ngược lại với Object.entries(): chuyển một iterable (mảng, Map, Set...) chứa các cặp [key, value] thành một Object.
Cú pháp
Object.fromEntries(iterable)
iterable: Phải là đối tượng lặp được (Array, Map, Set, Generator...) chứa các cặp [key, value].
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Object.fromEntries()</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 18px; font-weight: 500; font-family: monospace; }
.result { color: green; }
button { padding: 8px 16px; cursor: pointer; }
pre { background: #f5f5f5; padding: 10px; border-radius: 4px; }
</style>
</head>
<body>
<h1>Object.fromEntries() method</h1>
<div class="sample"><pre>[['firstName','Rohan'],['lastName','Sharma'],['age',22]]</pre></div>
<div class="result">Object = <br></div>
<button class="btn-demo">CHUYỂN ĐỔI</button>
<h3>Nhấn nút để chuyển mảng cặp key-value thành Object</h3>
<script>
const resEle = document.querySelector(".result");
const btn = document.querySelector(".btn-demo");
// Mảng các cặp [key, value]
const arr = [
['firstName', 'Rohan'],
['lastName', 'Sharma'],
['age', 22]
];
btn.addEventListener("click", () => {
const obj = Object.fromEntries(arr);
resEle.innerHTML = "Object = <br>";
for (const key in obj) {
resEle.innerHTML += 'Key = ' + key + ' : Value = ' + obj[key] + '<br>';
}
});
</script>
</body>
</html>
Các trường hợp sử dụng phổ biến
1. Chuyển Map thành Object
const map = new Map([
['name', 'John'],
['age', 30]
]);
const obj = Object.fromEntries(map);
// { name: 'John', age: 30 }
2. Lọc/biến đổi properties của Object
const user = { id: 1, name: 'A', password: 'secret', email: 'a@b.com' };
// Loại bỏ password
const safeUser = Object.fromEntries(
Object.entries(user).filter(([key]) => key !== 'password')
);
// { id: 1, name: 'A', email: 'a@b.com' }
// Đổi tên key
const renamed = Object.fromEntries(
Object.entries(user).map(([key, val]) => [key.toUpperCase(), val])
);
// { ID: 1, NAME: 'A', PASSWORD: 'secret', EMAIL: 'a@b.com' }
3. Từ URLSearchParams
const params = new URLSearchParams('name=John&age=30&city=NY');
const obj = Object.fromEntries(params);
// { name: 'John', age: '30', city: 'NY' }
Lưu ý quan trọng
- Nếu có key trùng lặp, cặp sau sẽ ghi đè cặp trước.
- Nếu iterable chứa phần tử không phải cặp
[key, value](length != 2), sẽ némTypeError. - Không hỗ trợ IE (cần polyfill).
So sánh: entries() vs fromEntries()
const obj = { a: 1, b: 2 };
// Object → Array cặp
Object.entries(obj);
// [ ['a', 1], ['b', 2] ]
// Array cặp → Object
Object.fromEntries([ ['a', 1], ['b', 2] ]);
// { a: 1, b: 2 }
// Round-trip
Object.fromEntries(Object.entries(obj)); // { a: 1, b: 2 }