user7632903
user7632903

Reputation: 11

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

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

    }
  }

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

"[email protected]"
"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?

Upvotes: 1

Views: 4898

Answers (3)

Harsh Vitra
Harsh Vitra

Reputation: 31

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

    }
  }

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

Upvotes: 0

Cauterite
Cauterite

Reputation: 1694

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": "[email protected]", "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:

[["[email protected]", "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:

["[email protected]", "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)))

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

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

Upvotes: 1

Related Questions