-1

I am currently working on a project in Javascript. I have an array of String objects that I would like to iterate through. However, I cannot figure out how to access the Key of each property of the objects.

For example:

var jsonDoc = [
    {
        "Subject": "XXXXXXX",
        "Submitter": "X",
        "Dx": "Affected",
        "Sample Set": "Arab",
        "Sex": "F",
            "Pedigree": "0"
    },
    {
            "Subject": "XXXXXXX",
            "Submitter": "X",
            "Dx": "Affected",
            "Sample Set": "North American",
            "Sex": "F",
            "Pedigree": "0"
    }
]

for( var i = 0; i<jsonDoc.length; i++){
    for(var key in jsonDoc[i]){
        document.write(jsonDoc[i][key]+"<br />");
     }
    document.write("--- <br />");
}

However, this only prints the values and not the keys:

XXXXXXX
X
Affected
Arab
F
0
---
XXXXXXX
X
Affected
North American
F
0
---

How can I access the Subject, Submitter, etc in an iterative fashion?

user2465164
  • 917
  • 4
  • 15
  • 29

1 Answers1

5

you already have the key in the value of the key variable in the inner for loop

just change your code to

for( var i = 0; i<jsonDoc.length; i++){
    for(var key in jsonDoc[i]){
        document.write(key + ': '+ jsonDoc[i][key]+"<br />");
     }
    document.write("--- <br />");
}

and you'll see :)

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68