如何检查嵌套对象的值是否已存在于另一个对象中?

How to check if a value of a nested object already exists in another one?

我的 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"
  }
}

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

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

//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.
}

您需要执行以下几个步骤:

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

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