-2

I have a JavaScript Object named "userinfo" (it stored some user's info). And I want to access value by key in it. For all the keys I can success get, except one key named "auths". And then I print it in console by console.log(userinfo), it shown as well. And while I traversal it Object, the key don't show again...

And then I click the option "Store as global variable" in Chrome debug console. And not when I try to access, it works well.

Here it's my code and debug's screenshot.

    console.log(userinfo);

    for (var key in userinfo){
        console.log(key + " = " + userinfo[key]);
    }

Because here some my really personal informations in it, I produced this picture.(Position I've printed "hide info").

I want to know why the code working not well, and how can I access the info stored in key "auths".

Thanks!

screenshot of debuging

桂小方
  • 41
  • 1
  • 2
  • 6
  • Please, get used to add code as plain text (you can format it in the editor) – Alfabravo Feb 06 '18 at 19:17
  • you could easily find out by accessing it hardcoded e.g `userinfo['auths']` before the loop – john Smith Feb 06 '18 at 19:23
  • So is `userinfo` dynamically loaded? My educated guess is yes and you are trying to eat the delievery pizza before it gets delivered to your house. console.log of objects is NOT a snapshot in the time it was written. – epascarello Feb 06 '18 at 19:24
  • Thanks! It's true that the `auths` property was add after I used GET from my API, so how can I get this property in Object `userinfo`? – 桂小方 Feb 06 '18 at 19:25
  • 1
    You wait until it is loaded to read it. – epascarello Feb 06 '18 at 19:26
  • https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello Feb 06 '18 at 19:30

1 Answers1

2

console.log is deceiving. It's printing a "live" object. If object is altered after it's been logged, the log will update (you'll see the new property when you expand the object in the log). Naturally, this doesn't apply to the temp strings you build there with concatenation. So yes, I'd bet 10 bucks that the object does not indeed have auths property at the time of printing. It is added later.

Observe this in action (look in browser's console)

var myobj = { foo: 1 }
console.log(myobj);
myobj.bar = 2;
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367