我正在尝试序列化一个具有大约一百个属性的javascript对象。其中3个实现为在访问它们时记录警告(可能使用属性getter实现)。
我希望序列化对象
除了
这3个属性,而且我甚至不想访问这3个特性。
我尝试了以下操作(使用替换器函数):
const excludeProperties = ['badProp1', 'badProp2', 'badProp3']
JSON.stringify(theObject, (key, value) => excludeProperties.includes(key) ? undefined : value);
虽然最终结果确实将属性从JSON中排除,但不幸的是,它并不能阻止这些属性在幕后被访问,因此仍然会抛出警告。
有人能想出一个相当简单(代码更少)的解决方案来确保这些密钥永远不会被访问吗?
复制步骤:
const obj = {
goodProperty: "Serialize Me",
get badProperty() {
console.log("Warning: Accessed deprecated property")
return "deprecated";
}
};
console.log(JSON.stringify(obj));
// Output:
// Warning: Accessed deprecated property
// {"goodProperty":"Serialize Me","badProperty":"deprecated"}
const excludeProperties = ["badProperty"];
console.log(JSON.stringify(obj, (key, value) => excludeProperties.includes(key) ? undefined : value));
// Output:
// Warning: Accessed deprecated property
// {"goodProperty":"Serialize Me"}