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

问题描述

我的 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","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 作为 @robin-dijkhof 提到
  • form.setValue( … )传递the object of the user
  • 检查表单是否有效 - 应该是用户数据是否通过所有验证

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