JSON.stringify() tự động loại bỏ property có giá trị là function (cũng như undefined, Symbol) khi serialize object.
Ví dụ 1: Property là function
<script>
const person = {
name: 'Rahim',
designation: function() { return 'Developer'; }, // Function property
city: 'Hyderabad'
};
const json = JSON.stringify(person);
document.write(json);
// {"name":"Rahim","city":"Hyderabad"} — designation MẤT
</script>
Ví dụ 2: Property name là function
<script>
const person = {
name: function() { return 'Ram + Rahim'; }, // Function property
designation: 'Developer',
city: 'Hyderabad'
};
const json = JSON.stringify(person);
document.write(json);
// {"designation":"Developer","city":"Hyderabad"} — name MẤT
</script>
Tại sao? Theo JSON Spec
- JSON chỉ hỗ trợ: String, Number, Boolean, Null, Object, Array.
- Function, Undefined, Symbol không có biểu diễn JSON → bị skip.
Các giá trị bị loại bỏ
| Giá trị | JSON.stringify behavior |
|---|---|
| Function | Bỏ qua (skip property) |
| Undefined | Bỏ qua (skip property) |
| Symbol | Bỏ qua (skip property) |
| NaN, Infinity, -Infinity | Tr thành null |
| Date | Tr thành ISO string (toJSON) |
| RegExp, Error | Tr thành {} |
Custom Replacer để kiểm soát
const obj = {
name: 'Alice',
compute: () => 'secret',
password: '123456'
};
// Replacer function: trả về undefined để skip, hoặc giá trị để include
const json = JSON.stringify(obj, (key, value) => {
if (key === 'password') return undefined; // Ẩn sensitive
if (typeof value === 'function') return value.toString(); // Giữ function as string
return value;
});
console.log(json);
// {"name":"Alice","compute":"() => 'secret'"}
Lưu ý
- Replacer không thể thêm property mới — chỉ lọc/biến đổi existing.
- Để include function: convert to string trước (như bài trước) hoặc dùng custom serializer.
- Deep clone không mất function:
structuredClone(obj)(modern) hoặclodash.cloneDeep.