var formmd = {
  "frmType": "Registration",
  "frmStage": "step1-complete",
  "formattr": {
    "SystemUser": {
      "LoginName": "[email protected]",
      "Password": "password",
      "PIN": "",
      "IsTestUser": false
    },

    "ConsumerAddress": {
      "AddressLine1": "201 MOUNT Road",
      "AddressLine2": null,
      "AddressTypeId": "1",
      "City": "OLA TRAP",
      "State": "NM",
      "Zipcode": "60005"
    },
    "ConsumerPhone": {
      "PhoneTypeId": 6,
      "PhoneNumber": "9876543210",
      "PrimaryPhoneIndicator": null,
      "AllowVoicemail": false
    },

    "PhysicianSpecialty": {
      "SpecialtyList": [
        "1",
        "2"
      ]
    },

    }
  }


我正在尝试在formattr下获取子对象的所有值,但无法在子对象内部进行迭代。以下是我尝试过的脚本。
我的结果应该是

"[email protected]"
"password"
"PIN": ""
False
201 MOUNT Road"


我尝试的脚本是

function walk(formmd) {
    var obj1 = formmd.formattr;

    for(var key in obj1){
        if (obj1.hasOwnProperty(key)) {
            var val1 = obj1[key];

            if(val1.hasOwnProperty(key)){
             for(var key in val1){
                var val2 =val1[key];

                console.log("val2");
                }
            }
        }
    }
}


如何自动访问子对象的键?

最佳答案

这样尝试

for (var key in formmd) {
  var val1 = formmd[key];
  if (key=="formattr") {
    for (var key1 in val1) {
      var val2 = val1[key1];
      for(var key2 in val2)
      console.log(val2[key2]);
    }
  }
}


DEMO

08-04 16:34