Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa function khỏi object bằng JSON.stringify() trong JavaScript

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
FunctionBỏ qua (skip property)
UndefinedBỏ qua (skip property)
SymbolBỏ qua (skip property)
NaN, Infinity, -InfinityTr thành null
DateTr thành ISO string (toJSON)
RegExp, ErrorTr 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ặc lodash.cloneDeep.