Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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't access it with config.col_id_3 (see the "undefined" in the screenshot?). Can anyone explain this? I can get access to every other property except field_id_4 as well.

console.log(config); console.log(config.col_id_3); 

This is what these lines print in Console

Console output

like image 227
Brian Litzinger Avatar asked Jul 09 '13 11:07

Brian Litzinger


People also ask

How do you display an object in console log?

Answer: Use console. log() or JSON. stringify() Method log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.

Why is object property undefined JavaScript?

Undefined value primitive value is used when a variable has not been assigned a value. The standard clearly defines that you will receive undefined when accessing uninitialized variables, non-existing object properties, non-existing array elements, and alike.

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .


1 Answers

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.

like image 187
Matt Avatar answered Oct 17 '22 08:10

Matt