简体   繁体   中英

Iterate through the child objects and get all the values with javascript

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"
      ]
    },

    }
  }

I'm trying to fetch all the values of the child objects under formattr but I'm unable to iterate inside the child objects. The following is the script I tried. My Result should be

"A@test.com"
"password"
"PIN": ""
False
201 MOUNT Road"

The script I tried is

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");
                }           
            }               
        }           
    }
}

How to access the keys of child objects in an automated way?

Try like this

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

You might find it easier to understand code written in a functional style. This is one solution, which I'll explain:

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

The first expression Object.values(formmd.formattr) gives you an array of all the values (not keys) under formmd.formattr . Something like:

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

Since you want the values within each of these sub-objects the next line .map(obj => Object.values(obj)) will do just that. It returns a new array where each object in the input array is transformed through Object.values(…) . It returns something like:

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

This array has all the data you're after, but in nested arrays, so it needs to be flattened with .reduce((acc, vals) => acc.concat(vals), []) . This reduce will successively concat these sub-arrays to produce a single array like:

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

which contains all the values of the child objects under formattr .


Here's some other ways to do it:

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

or

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

You will have to use Object.entries()

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well).

Example -

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

Code Snippet -

 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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM