0

I have an object with multiple objects, and need to create a loop for each key within each object.

I need the console to log something like this.

Iron
TIBC
carbon dioxide
Sodium
etc...

This is what I have tried so far

(function() {
  var blood = {
    "blood": {
      "one": {
        "iron": "Iron",
        "tibc": "TIBC",

      },
      "two": {
        "cd": "Carbon Dioxide",
        "sodium": "Sodium",
        "potassium": "Potassium",
        "chloride": "Chloride",
      },
      "three": {
        "cholesterol": "Cholesterol",
        "dhdl": "Direct HDL",
      },
      "four": {
        "rigg": "Rubella IgG",
        "hbsag": "HBsAg",
        "ahiv": "Anti-HIV 1+2",
        "estrdiol": "Estradiol",
        "fsh": "FSH",
      }
    }
  }

  for (var key in blood) {
    if (blood.hasOwnProperty(key)) {
      var newKey = blood[key]

      for (var key in newKey) {
        if (newKey.hasOwnProperty(key)) {
          //do stuff
          console.log(newKey[key])
        }
      }

    }
  }
})

4
  • Your code re-uses "key" inside the outer loop. It would work better (in newer JavaScript environments) if you declared the variables with let instead of var. Commented Sep 14, 2017 at 16:10
  • Your inner loop is overwriting the variable key try changing it to a different name Commented Sep 14, 2017 at 16:10
  • 1
    You're also not executing your IIFE (place () at the very end!) Commented Sep 14, 2017 at 16:10
  • @brenjt It never reuses the variable in that loop, so it shouldn't cause a failure, but I agree it's bad form. Commented Sep 14, 2017 at 16:12

4 Answers 4

1

Thats what Object.values is for:

 const result = Object.values( blood.blood ).map(
   obj => Object.values(obj).join("\n")
 ).join("\n");

 console.log( result );
Sign up to request clarification or add additional context in comments.

Comments

0

Like this?

You are looping through the keys with a for loop, so by recursively calling the same for loop and showing the output only if the value of the object is a string, we can get the desired output, if its type is object then call the function again.

var blood = {
  "blood": {
    "one": {
      "iron": "Iron",
      "tibc": "TIBC",

    },
    "two": {
      "cd": "Carbon Dioxide",
      "sodium": "Sodium",
      "potassium": "Potassium",
      "chloride": "Chloride",
    },
    "three": {
      "cholesterol": "Cholesterol",
      "dhdl": "Direct HDL",
    },
    "four": {
      "rigg": "Rubella IgG",
      "hbsag": "HBsAg",
      "ahiv": "Anti-HIV 1+2",
      "estrdiol": "Estradiol",
      "fsh": "FSH",
    }
  }
}

function keyGetter(data){
  for(key in data){
    if(typeof data[key] === typeof ""){
      console.log(data[key]);
    }else{
      keyGetter(data[key]);
    }
  }
}
keyGetter(blood);

3 Comments

Please explain what the problem was and how you fixed it. Also, click the Tidy button in the snippet.
@user2168066 can you check my answer again, I applied recursion and got the keys alone, this is a bit more confusing but lesser coding and a better thing to use!
@Barmar Thanks, I made the corrections, sorry usually I edit my answer after I post it!
0

You can get all the values into an array with the following:

let allTypes = [];

Object.values(blood.blood).forEach(v => {
  // we are iterating over "one"..."four"
  allTypes.push(...Object.values(v));
});

console.log(allTypes);

Will output ["Iron", "TIBC", "Carbon Dioxide", "Sodium", "Potassium", "Chloride", "Cholesterol", "Direct HDL", "Rubella IgG", "HBsAg", "Anti-HIV 1+2", "Estradiol", "FSH"].

https://jsbin.com/kodolok/edit?js,console

Object.values is really useful when iterating over objects that are basically associative arrays.

Comments

0

I made a recursive function that may help you!

var blood = {
        "blood": {
            "one": {
                "iron": "Iron",
                "tibc": "TIBC",

            },
            "two": {
                "cd": "Carbon Dioxide",
                "sodium": "Sodium",
                "potassium": "Potassium",
                "chloride": "Chloride",
            },
            "three": {
                "cholesterol": "Cholesterol",
                "dhdl": "Direct HDL",
            },
            "four": {
                "rigg": "Rubella IgG",
                "hbsag": "HBsAg",
                "ahiv": "Anti-HIV 1+2",
                "estrdiol": "Estradiol",
                "fsh": "FSH",
            }
        }
}

loopThrough(blood)

function loopThrough(obj){
   if(typeof obj == "object"){
     for(var i in obj){
       loopThrough(obj[i]);
     }
   }else{
     console.log(obj)
   }
  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.