【问题标题】:How to check if a value of a nested object already exists in another one?如何检查嵌套对象的值是否已存在于另一个对象中?
【发布时间】:2021-06-08 08:41:56
【问题描述】:

我在我的 Angular 应用程序中有一个函数,我必须在其中检查表单的属性并检查哪些具有属性“required”= true,然后检查用户之前是否已经输入了此信息。通过此验证,如果相应的用户信息已经存在,我将跳过该表单,否则我将显示该表单。

更新

我已经通过几个“foreach”检查它们是否具有值,但我被困在这一点上,我不知道如何解决我需要做的事情。

函数如下


      const initForm = getInitForm();
      const user = getUser();
      const dataNotFilled = [];

      initialForm.props.forEach((prop) => {
        if (prop.required) {
          const nestedObjectData = {};

          Object.keys(user).forEach((initKey) => {

            const value = user[initKey];

            if (initKey === prop.name && value === null) {

              dataNotFilled.push(value);

            } else if (typeof value === 'object') {

              Object.assign(nestedObjectData, value);

              Object.keys(nestedObjectData).forEach((key) => {

                const nestedValue = nestedObjectData[key];

                if (key === prop.name && nestedValue === null) {

                  dataNotFilled.push(nestedValue);

                }

              });

            }

          });

          if (dataNotFilled.length) {
            browserHistory.push(ADD_USER_DATA_PATH);
          }

        }

      });

   


这是我收到的表单所需数据的对象


{
  "label": "city",
  "name": "city",
  "type": "text",
  "parent": "primaryAddress",
  "validations": [
    {
      "message": "error",
      "value": {
        "pattern": "^\\d{2}-\\d{3}$|\\d{5}"
      },
      "rule": "regex"
    },
    {
      "message": "required",
      "value": true,
      "rule": "required"
    }
  ],
  "required": true,
  "services": []
}

这是用户的对象


{
  "name": "John",
  "surname": "Martin",
  "email": null,
  "address": null,
  "phone": {
    "home": null,
    "mobile": null
  },
  "address": {
    "code": "null",
    "address": null,
    "city": "Kansas"
  }
}

如果信息已经存在,我如何比较两个对象的属性以跳过表单? 提前感谢大家的时间和帮助。

【问题讨论】:

  • 你在使用reactive forms吗?如果是,那么你可以去Array<Forms>

标签: angular object foreach nested comparison


【解决方案1】:

我认为你把它弄得太复杂了。为什么不简单地做这样的事情:

//Fill the form with your initial object, if any.
this.form = formBuilder.group({
    name: [{value: initialObject.name, disabled: initialObject.name !== null}] // Or '' or undefined
    surname: [{value: initialObject.surname, disabled: initialObject.surname !== null}]
})


// Other logic.

if(form.valid){
    // Form is instantly valid so skip it.
}

【讨论】:

    【解决方案2】:

    您需要遵循几个步骤:

    • 使用the object of the required data 构建表单(为此使用一些递归函数)和formBuilder 作为@robin-dijkhof 提到的
    • form.setValue( … )通过the object of the user
    • 检查表单是否有效 - 应该是用户数据是否通过所有验证

    使用 angular 提供的预定义 Validators.pattern / Validators.required ;)

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多