Can't access object property, even though it shows up in a console log

后端 未结 30 2114
日久生厌
日久生厌 2020-11-22 06:26

Below, you can see the output from these two logs. The first clearly shows the full object with the property I\'m trying to access, but on the very next line of code, I can\

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 07:05

    I had an issue like this, and found the solution was to do with Underscore.js. My initial logging made no sense:

    console.log(JSON.stringify(obj, null, 2));
    
    > {
    >   "code": "foo"
    > }
    
    console.log(obj.code);
    
    > undefined
    

    I found the solution by also looking at the keys of the object:

    console.log(JSON.stringify(Object.keys(obj)));
    
    > ["_wrapped","_chain"]
    

    This lead me to realise that obj was actually an Underscore.js wrapper around an object, and the initial debugging was lying to me.

提交回复
热议问题