Why javascript cannot access some object by key? - javascript

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!

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;

Related

Object values are changed as soon as I open it

I am working with Javascript/ReactJS code, I am printing the Object(Obj), containing keys as ids and values as the status(true/false) of the corresponding keys in the console. The desired Object is printed, but as soon as I opened that object, it automatically changed its values.
the first property of this object is true, but when I open it, it goes false.
I declare that Object(Obj) outside the render method because it renders JSX every time either it needed or not. But it is not working.
render(){
return defaultApp(templates).map(template=>{
Obj[`${template._id}`] = false;
return <Apps id={template._id}
onClick={this.handleToggle.bind(this)}>
<h2>{template.title}</h2>
</Apps>
});
}
handleToggle = (e)=>{
var selectedAppId = e.target.id?e.target.id:e.target.parentNode.id;
if(!isEmpty(Obj)) {
Object.keys(Obj).forEach((id)=>{
if(selectedAppId===id){
Obj[selectedAppId] = !Obj[selectedAppId];
console.log(Obj);
this.setState({currentAppId:id,AppsStatus:Obj});
}});
}
I want to see the same Object's values either I open it or not.
console JSON.stringify(obj) to check the exact object values.
Remember objects are references so if their key values are changed at any point of the program, the change will be reflected all over the code as all the variables are storing the reference to that object.

My object is not recognizing the key that is already been set

I have this snippet of code (unfortunately it won't work for you unless you have a qualtrics account and go into preview survey and run it in the console) that keeps throwing the error (Cannot set property 'questions0' of undefined). Yet I just added an object named ArrayOfBlocks2 to the main object. Can someone tell my why its saying ArrayOfBlocks2 is undefined?
Qualtrics.SurveyEngine.setEmbeddedData("ArrayOfBlocks",ArrayOfBlocks)
var ArrayOfBlocks1 = Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")
for(i=0;i<Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks").length;i++){
for(k=0;k<Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")[i].BlockElements.length;k++){
var ArrayOfBlocks2 = ArrayOfBlocks1[i].ID
console.log(ArrayOfBlocks2)
ObjectIDWithQuestions[ArrayOfBlocks2]={}
Qualtrics.SurveyEngine.setEmbeddedData("OBID",ObjectIDWithQuestions);
ObjectIDWithQuestions.ArrayOfBlocks2["questions"+ k]=Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")[i].BlockElements[k].QuestionID
Qualtrics.SurveyEngine.setEmbeddedData("ObjectIDWithQuestions",ObjectIDWithQuestions)
}
}
I expect it to not throw an error, and to set "questions + k" as a object key.
Embedded data won't store an array by default, you will likely need to json encode the data before storing, and json parse the data on retrieval.

chrome debugger inconsistency in object data

I don't understand how to interpret this debug data. I do a console.log of my object, and on the summary-line that appears in the console I am shown windows: array[0] but if I expand the object, I am shown that windows is an array of 2 items.
Which is the correct one?
My code seem to run on the summary version, ie. windows array being empty.
Does anyone know what my problem is - why is the object presented in an inconsistent way?
The object is being mutated between when you print it and when you view it. When it's initially logged, it's empty but by the time you open it, 2 items have been added.
var obj = { arr: [] };
console.log(obj); // Will say { arr: Array[0] }
obj.arr.push(1); // Open it up in the console after this
Basically, the dev tools print a string that's representative of it's state at the time of the log but it stores a reference to the object in the console itself.

Pushing various objects in Javascript but save not properly

I'm pushing various objects in an array.
$scope.itemsPending = [];
while(bonos.length > 0){
if($scope.itemsPending.length > 0){
console.log($scope.itemsPending);
}
bono = bonos.shift();
if(bono.is_highlighted == false){
aux.push(bono);
maximo++;
}else{
if(maximo + 2 < 4){
aux.push(bono);
maximo += 2;
}else{
$scope.itemsPending.push(bono);
}
}
}
But when I show it in the dev console I have one or two "objects" and if I open this items, I have three.
What is happening?
EDIT
My bono value is like that
Chrome's console (for better or for worse) "logs" a reference to the object and when you inspect its contents by clicking on the arrow, it shows the current value at that object. This means that modifying an array within a loop and logging it on each iteration might have unexpected results.
Here is a simplified example demonstrating the issue. You should see the array being logged 3 times as [Object], [Object, Object], [Object, Object, Object], but "expanding" each of these logs will access the current contents of the array and show you 3 elements in all cases.
To reliably log changes to an object, log a primitive value instead of an object or an array. For example, the length of the array, or a serialized version of the array.
Also, consider that in the alternative (in order to show the state of the object at the time it was logged), the browser would need to clone and retain every object that is logged. This would cause it to run out of memory very quickly.

Updating a part of the object works but it updates even before I update it

Im updating a part of an object and the update works fine.Its when I did a console.log on the object before the I called the update functio,n the object was already updated.I was expecting to see the old copy of the object,i know Im doing something really silly.I just want to understand why this is happening.Here is my code
function updateObject(o){
o.a='oneHundred';
o.b='twoHundred'
}
var obj={
a : 'one',
b : 'two',
c : {
a : '',
b : ''
}
}
console.log(obj);//outputs the updated object before I call updateObject()
var upObject = obj.c ;
updateObject(upObject);
console.log(obj);
Chrome (and possibly firebug) doesn't actually log the current state of an object until you observe it. If you put a breakpoint in the code like so:
console.log(obj);//outputs the updated object before I call updateObject()
debugger; // force breakpoint
var upObject = obj.c ;
updateObject(upObject);
console.log(obj);
and then expand the object you will see that it's the un-updated version. You're better off logging the specific properties you want to see rather than entire objects when you can.
Chrome will display the object itself in the console, not a representation of the object at that point in time. You can call stringify to get a snapshot and log that so it won't change when you change the object.
console.log(JSON.stringify(obj));

Categories

Resources