代码之家  ›  专栏  ›  技术社区  ›  Alain

是否在不访问某些键的情况下序列化对象?

  •  0
  • Alain  · 技术社区  · 2 年前

    我正在尝试序列化一个具有大约一百个属性的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"}
    0 回复  |  直到 2 年前
        1
  •  0
  •   0stone0    2 年前

    你可以使用 reduce() 在…上 Object.keys(obj) 创建一个仅具有所需属性的新对象。这样它就不会触发getter。

    使用spread语法会触发它,所以这不是一个选项。

    const obj = {
      goodProperty: "Serialize Me",
      get badProperty() {
        console.log("Warning: Accessed deprecated property")
        return "deprecated";
      }
    };
    
    const excludeProperties = ["badProperty"];
    
    const objWithoutBadProperties = Object.keys(obj).reduce((p, c) => {
        if (!excludeProperties.includes(c)) {
            p[c] = obj[c];
        }
        return p;
    }, {});
    console.log(JSON.stringify(objWithoutBadProperties));