遍历子对象并使用javascript获取所有值

时间:2017-02-28 02:49:05

标签: javascript json loops object

var formmd = {
  "frmType": "Registration",
  "frmStage": "step1-complete",
  "formattr": {
    "SystemUser": {
      "LoginName": "A@test.com",
      "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下获取子对象的所有值,但是我无法在子对象内部进行迭代。以下是我试过的脚本。 我的结果应该是

"A@test.com"
"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");
                }           
            }               
        }           
    }
}

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

3 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:0)

您可能会发现理解以功能样式编写的代码更容易。这是一个解决方案,我将解释:

Object.values(formmd.formattr)
    .map(obj => Object.values(obj))
    .reduce((acc, vals) => acc.concat(vals), [])

第一个表达式Object.values(formmd.formattr)为您提供formmd.formattr下所有值(而不是键)的数组。类似的东西:

[{"LoginName": "A@test.com", "Password": "password", …}, {"AddressLine1": "201 MOUNT Road", "AddressLine2": null, …}, …]

由于你想要每个子对象中的值,下一行.map(obj => Object.values(obj))就是这样做的。它返回一个新数组,其中输入数组中的每个对象都通过Object.values(…)进行转换。它返回类似于:

[["A@test.com", "password", "", false], ["201 MOUNT Road", null, "1", …], …]

此数组包含您之后的所有数据,但在嵌套数组中,因此需要使用.reduce((acc, vals) => acc.concat(vals), [])展平。这个reduce将连续concat这些子数组生成单个数组,如:

["A@test.com", "password", "", false, "201 MOUNT Road", null, "1", …]

,其中包含formattr下的子对象的所有值。

以下是其他一些方法:

Object.values(formmd.formattr)
    .reduce((acc, x) => acc.concat(Object.values(x)), [])

[].concat(...
    Object.values(formmd.formattr)
        .map(obj => Object.values(obj)))

答案 2 :(得分:0)

您将不得不使用Object.entries()

Object.entries()方法返回给定对象自己的数组 可枚举的字符串键属性[key,value]对,顺序相同 如for ... in循环所提供的那样。 (唯一重要的区别是 for ... in循环枚举原型链中的属性为 好)。

示例-

for (const [key, value] of Object.entries(objectName)) {
  console.log(`${key}: ${value}`);
}

代码段-

var formmd = {
  "frmType": "Registration",
  "frmStage": "step1-complete",
  "formattr": {
    "SystemUser": {
      "LoginName": "A@test.com",
      "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"
      ]
    },

    }
  }

for (const [key, value] of Object.entries(formmd.formattr)) {
  console.log('Value',value);
}