0

My json object is

"lastModifyingUser": {
"kind": "drive#user",
"displayName": string,
"picture": {
  "url": string
},
"isAuthenticatedUser": boolean,
"permissionId": string

}

I want to loop through lastModifyingUser and pull only the url value from the picture object.

Is this possible?

here is what I have so far.

var obj = resp.lastModifyingUser;


                for(var k in obj){
                    var value = obj[k];
                    console.log(value);
                }   

output :

drive#user 
#Hidden Name
Object {url: "#Hidden URL"}  <-- I want only the "hidden" URL
false 
#Hidden Id
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Joe
  • 267
  • 1
  • 6
  • 17

2 Answers2

1

Something like

for(var k in obj)
{
    var value = obj[k].url || obj[k];
    console.log(value);
}

will do what you want, but bear in mind it's a quick and dirty solution. You'd probably want to some kind of basic type checking and hasOwnProperty checks to make sure you're not going to throw errors or pull in prototype fields accidentally (unlikely if this is json straight from an API, but it's still a good idea to do it).

RedBrogdon
  • 5,113
  • 2
  • 24
  • 31
1

A recursive function would more elegant, but the following should work:

for(var k in obj) {
    var value = obj[k];
    if (typeof value === 'object') {
        for (var k2 in value) {
            var value2 = value[k2];
            console.log(value2);
        }
    } else {
        console.log(value);
    }
}  
76484
  • 8,498
  • 3
  • 19
  • 30