8

I have an object that looks like this:

var myObj = {
    name:"Bacon",
    fat:20,
    carb:40
}

Is there a way to do a loop on the keys of the object, to then get its value?

2 Answers2

8

You can traverse through javascript following way:

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    alert(key + " -> " + p[key]);
  }
}
Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32
André Perazzi
  • 1,039
  • 2
  • 11
  • 27
1

This should work.

for (var key in myObj) {
   if (myObj.hasOwnProperty(key)) {
       var obj = myObj[key];
        for (var prop in obj) {
          if(obj.hasOwnProperty(prop)){
            alert(prop + " = " + obj[prop]);
          }
       }
    }
}
Joshua
  • 5,901
  • 2
  • 32
  • 52