Can't access object property, even though it shows up in a console log
The output of console.log(anObject)
is misleading; the state of the object displayed is only resolved when you expand the Object tree displayed in the console, by clicking on >
. It is not the state of the object when you console.log
'd the object.
Instead, try console.log(Object.keys(config))
, or even console.log(JSON.stringify(config))
and you will see the keys, or the state of the object at the time you called console.log
.
You will (usually) find the keys are being added after your console.log
call.
I've just had this issue with a document loaded from MongoDB using Mongoose.
When running console.log()
on the whole object, all the document fields (as stored in the db) would show up. However some individual property accessors would return undefined
, when others (including _id
) worked fine.
Turned out that property accessors only works for those fields specified in my mongoose.Schema(...)
definition, whereas console.log()
and JSON.stringify()
returns all fields stored in the db.
Solution (if you're using Mongoose): make sure all your db fields are defined in mongoose.Schema(...)
.
Check if inside the object there's an array of objects. I had a similar issue with a JSON:
"terms": {
"category": [
{
"ID": 4,
"name": "Cirugia",
"slug": "cirugia",
"description": "",
"taxonomy": "category",
"parent": null,
"count": 68,
"link": "http://distritocuatro.mx/enarm/category/cirugia/"
}
]
}
I tried to access the 'name' key from 'category' and I got the undefined error, because I was using:
var_name = obj_array.terms.category.name
Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:
var_name = obj_array.terms.category[0].name
And That does the trick.
Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)
I had the same issue. Solution for me was using the stringified output as input to parsing the JSON. this worked for me. hope its useful to you
var x =JSON.parse(JSON.stringify(obj));
console.log(x.property_actually_now_defined);