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?

1
  • 3
    This is not json, this is javascript object. Commented Jun 29, 2015 at 3:18

2 Answers 2

8

You can traverse through javascript following way:

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    alert(key + " -> " + p[key]);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.