const name = "An";
const key = "email";
const user = {
name, // viết tắt của name: name
age: 20,
[key]: "an@example.com", // computed key
"full name": "Nguyễn Văn An", // key có dấu cách phải để trong ""
greet() { // method shorthand
return `Chào ${this.name}`;
},
};user.age; // 20
user["full name"]; // dùng [] khi key động hoặc có ký tự đặc biệt
user.phone; // undefined (không lỗi)
user.address?.city; // undefined (không lỗi nhờ ?.)
user.age = 21; // sửa
user.phone = "0909"; // thêm
delete user.phone; // xóa
"age" in user; // true (tính cả thuộc tính kế thừa)
Object.hasOwnObject.keys(user); // ["name", "age", "email", "full name", "greet"]
Object.values(user);
Object.entries(user); // [["name", "An"], ["age", 21], ...]
// Biến đổi object qua entries
const prices = { ao: 200, quan: 300 };
const withVat = Object.fromEntries(
Object.entries(prices).map(([
const { name: fullName, age, country = "VN", ...rest } = user;
// fullName = "An", country mặc định "VN", rest chứa các thuộc tính còn lại
const { address: { city } = {} } = user; // lồng nhau + mặc định để tránh lỗiconst defaults = { theme: "light", lang: "vi" };
const settings = { ...defaults, theme: "dark" }; // thuộc tính sau ghi đè thuộc tính trước
const updated = { ...user, age: 22 }; // "cập nhật" bất biến — không sửa user gốcWARNING
Spread chỉ sao chép nông (shallow): object lồng bên trong vẫn dùng chung tham chiếu. Cần bản sao sâu thì dùng structuredClone(obj).
const config = Object.freeze({ api: "https://api.example.com" });
Object.isFrozen(config); // trueObject.freeze cũng chỉ nông. Muốn khóa cả object lồng nhau phải freeze đệ quy.
Comments