【问题标题】:JavaScript - Replace the values of a Nested Object, without affecting the whole objectJavaScript - 替换嵌套对象的值,而不影响整个对象
【发布时间】:2020-01-02 11:26:03
【问题描述】:

问题: 我有这个功能。这会从 Payload 中删除所有具有 Empty String 作为值的 KeyValue 对。

问题是,我想将它应用到嵌套的对象中。不是整个有效载荷对象。示例:

configuration: {
  conf1: "",
  conf2: "Something",
  conf3: ""
},
resourceName: "Name"

在这种情况下,我想在 configurationObject 中应用我的 UtilityFunction。这将导致:

configuration: {
  conf2: "Something",
},
resourceName: "Name"

所以,我使用了一些方法。 Object.assignrest,以便为对象提供所有外部参数,而且实用程序的输出仅应用于配置对象。

我试过了:

Object.assign(formValues, removeEmptyKeysUtil(formValues.configuration));
// Results in printing the values in the main object.

还有:

{ formValues, ...removeEmptyKeysUtil(formValues.configuration) };
// which does not do anything

你能帮我解释一下我做错了什么吗?

【问题讨论】:

    标签: javascript typescript object


    【解决方案1】:

    stripEmptyStrings 函数采用原始的objecttarget 键。 如果对象的目标属性是"",此函数也可以处理,并且无论它是否为对象,都会删除该属性。

    const stripEmptyStrings = (object, target) => {
      const _target = object[target];
      
      if (_target === "") {
        delete object[target]
        return object;
      }
      else if (typeof _target === "object") {
        Object.keys(_target).forEach((k) => {
          if (_target[k] === "") delete _target[k];
        })
      }
      
      return {
        ...object,
        [target]: _target,
      }
    }
    
    const obj1 = {
      configuration: {
        conf1: "",
        conf2: "Something",
        conf3: ""
      },
      resourceName: "Name",
    }
    const result1 = stripEmptyStrings(obj1, "configuration");
    console.log(result1)
    
    const obj2 = {
      removeMe: "",
      resourceName: "Name2",
    }
    const result2 = stripEmptyStrings(obj2, "removeMe");
    console.log(result2)

    【讨论】:

    • 你的回答非常正确。但我找到了另一种选择。您会看到该功能应该足够通用。因为它在多个地方使用。此外,数据是动态的,这会增加另一个难度。经过大量试验和错误后,我使用了以下内容:Object.assign({}, formValues, { configuration: removeEmptyKeysUtil(formValues.configuration) }) 这似乎工作得很好,将来它可以用作更多嵌套对象的引用。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2021-12-20
    • 2020-10-19
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多