Trong JavaScript, Dictionary (còn gọi là Map, Associative Array, Symbol Table) là cấu trúc dữ liệu lưu trữ cặp Key - Value. Có 2 cách chính: Object (truyền thống) và Map (ES6 - chuẩn, khuyên dùng).
1. Tạo Dictionary bằng Object (Cũ, phổ biến)
// Object literal
const dict1 = {
key1: "value1",
key2: "value2"
};
// Rỗng, thêm sau
const dict2 = {};
dict2.name = "An";
dict2["age"] = 25;
// Từ mảng cặp (ES2019 Object.fromEntries)
const entries = [["a", 1], ["b", 2]];
const dict3 = Object.fromEntries(entries); // { a: 1, b: 2 }
2. Tạo Dictionary bằng ES6 Map (Khuyên dùng)
// Rỗng
const map1 = new Map();
// Khởi tạo từ array cặp [key, value]
const map2 = new Map([
["key1", "value1"],
["key2", "value2"]
]);
// Từ Object (chỉ string key)
const obj = { a: 1, b: 2 };
const map3 = new Map(Object.entries(obj));
// Từ Iterable (Generator, Array, Map khác)
const map4 = new Map(map2); // Copy
3. Custom Dictionary Class (MyMap) - Học tập / Legacy
class MyMap {
constructor() {
this.container = {}; // Backend lưu trữ
}
// Hiển thị
display() {
console.log(this.container);
}
// Kiểm tra key tồn tại (Cần cho put/delete/get)
hasKey(key) {
return key in this.container; // Hoặc this.container.hasOwnProperty(key)
}
// Thêm/Sửa
put(key, value) {
this.container[key] = value;
}
// Lấy giá trị
get(key) {
if (this.hasKey(key)) return this.container[key];
return undefined;
}
// Xóa
delete(key) {
if (this.hasKey(key)) {
delete this.container[key];
return true;
}
return false;
}
// Xóa tất cả
clear() {
this.container = {};
}
// Lấy tất cả keys
keys() {
return Object.keys(this.container);
}
// Lấy tất cả values
values() {
return Object.values(this.container);
}
}
// Sử dụng
const myMap = new MyMap();
myMap.put("name", "An");
myMap.put("age", 25);
myMap.display(); // { name: 'An', age: 25 }
console.log(myMap.get("name")); // "An"
console.log(myMap.keys()); // ["name", "age"]
4. Kiểm tra Key tồn tại (Quan trọng)
| Cấu trúc | Cách kiểm tra | Lưu ý |
|---|---|---|
| Map (ES6) | map.has(key) | Chuẩn, O(1), an toàn |
| Object | key in obj | Kiểm tra cả prototype chain |
| Object | obj.hasOwnProperty(key) | Chỉ own property (an toàn hơn) |
| Object | obj[key] !== undefined | KHÔNG tin cậy (value có thể là undefined) |
// Map
const myMap = new Map([["key1", "value1"]]);
console.log(myMap.has("key1")); // true
console.log(myMap.has("key3")); // false
// Object
const obj = { key1: "value1" };
console.log("key1" in obj); // true
console.log(obj.hasOwnProperty("key1")); // true
console.log("toString" in obj); // true (từ prototype!)
console.log(obj.hasOwnProperty("toString")); // false
5. API Dictionary tiêu chuẩn (Các phương thức cần có)
get(key): Lấy valueput(key, value)/set(key, value): Thêm/Sửahas(key)/hasKey(key): Kiểm tra tồn tạidelete(key)/remove(key): Xóaclear(): Xóa tất cảkeys(): Lấy tất cả keys (Array/Iterable)values(): Lấy tất cả valuesentries()/[Symbol.iterator](): Lấy cặp [key, value]size/length: Số lượng phần tử
Khi nào dùng Dictionary?
- Tra cứu nhanh O(1) (Cache, Index, Symbol Table).
- Key unique (duy nhất).
- Thứ tự không quan trọng (Map ES6 giữ insertion order).
- Insert chậm hơn Array/Tree, Read nhanh.
Tóm lại: Tạo Dictionary JS: new Map() (ES6, khuyên dùng) hoặc Object literal {}. Map hỗ trợ key bất kỳ, size, iterable, perf tốt, an toàn prototype. Custom MyMap class cho mục đích học tập. Luôn dùng map.has(key) / obj.hasOwnProperty(key) để check key.