Thursday 17 January 2019

Traverse Object Structure Javascript






Possible Duplicate:
How do I enumerate the properties of a javascript object?






I have an object with keys like this:




var OBJ = {
"Some value": {val1: 53, val2: 43},
"Another one": {val1: 35, val2: 41},
"One More": {val1:32, val2: 43}
};


I want to traverse through it with a for loop, and use the val1 and val2 values. If this was an array, I'd just do this:




for(var i = 0; i < VAR.length; i++){
VAR[i].val1;
}


But how do I do this with an object that doesn't have a numberic key?



Thanks!


Answer



Try the following




for (var name in VAR) {
if (VAR.hasOwnProperty(name)) {
VAR[name].val1;
}
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...