Typescript/Javascript objects [duplicate] - javascript

This question already exists:
Why isn't my future value available now? [duplicate]
Closed 6 years ago.
I'm all the time learning. My question is: why this:
let user = {
firstname: '',
secondname: ''
}
let hz = new Horizon({host: "164.132.192.28:3100"});
let table = hz('users');
hz.connect();
table.find(1).fetch().subscribe((value) => {
user = {
firstname: value.firstname,
secondname: value.secondname
}
//OR:
user.firstname = value.firstname;
user.secondname = value.secondname;
});
console.log(user);
gives me this:
And why I can't get value?:
console.log(user.firstname);
//prints nothing
My third question: how to just save the results from query into an object and use it outside the query? If I use 'return' keyword then results are similar. I know it's a newbie question but I'm really struggling with this... Can someone help me?

The following line:
table.find(1).fetch().subscribe(...);
is calling asynchronous method. This means that provided callback will be called sometime later and not immediately at the moment when subscribe is called. Therefore when it comes to console.log() the browser prints out its string representation and at that moment both first and last name are have not yet being populated - thus empty fields. When later you click on the object to see its content in console - browser evaluates it at that moment and most likely the subscribe method has already finished - so you get your first and last name present.
Your code is actually saves data in the local user variable. The thing you must remember is that you should access it only after subscribe callback has been called.

Related

How to get array out of object in JS [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I was trying to get data from the notes array in the data object. I'm getting the object from mongodb and I want to get the array called notes. but I can't do it. for some reason. In java there is like Object.get(notes) and I can get a specific field within the object but I don't know how to do that in js. And I haven't been able to find something that works elsewhere online.
here is my code
axios.post('/api/user/notes')
.then(res => {
console.log( Object.values(res.data));
dataSet = Object.values(res.data);
console.log(dataSet[0]);
console.log(dataSet.notes[0]);
}).catch(err => {
console.log('it didnt work' + err);
});
image
dataSet is an array. So, to get the notes, you have to first select the first element of data, dataSet[0] and then the notes array. To get the first note, it would be dataSet[0].notes[0]. Also, beware that you are setting a global variable (perhaps on a browser's window object) when you type dataSet = ... What you probably want is to declare a variable local to the function with var dataSet = ...

Unable to access an array where the contents of said array are visible in Console.Log [duplicate]

This question already has answers here:
How can I make console.log show the current state of an object?
(12 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I setup a global variable to hold the data array:
var data = [];
This is a global variable as it is used outside of a function and needs to be accessible for all functions
I then iterate over a data set and populate the data array.
When I access this array using the console:
console.log(window.data);
I can see the following in Chromes console view:
There are many more records in the data set, they all follow exactly the same format
The issue I am having is, I cannot access this data array and am seeing zero length as shown below:.
console.log(window.data.length); // returns 0
I'm not clear on why this is occurring and am hoping someone can point out what I am doing wrong.
It seems like the result of processing this array is not available at the time I am trying to get the length, therefore I am getting zero.
Have tried the following at the end of the html file:
$( document ).ready(function() {
console.log("ready!"); // returns ready!
console.log(window.data[15]); // returns undefined
});
Not quite sure how to proceed, so any advice would be very welcome.
EDIT:
This was resolved by the use of promises (bottom link in the duplicate notice above).
Previous code was removed as it didn't add to the discussion and would probably only create confusion
Core issue was based on data not being available on page load due to processing of large arrays.

logging javascript object properties [duplicate]

This question already has answers here:
console.log() async or sync?
(3 answers)
console.log() shows the changed value of a variable before the value actually changes
(7 answers)
Closed 5 years ago.
Please share your thoughts regarding below outputs.
var a = '';
console.log(a); //this logs nothing as expected.
a = 'triven';
var a = {};
console.log(a); // How javascript is aware of property here that is defined below.
a.name = 'triven';
I think you're looking for console.dir().
console.log() doesn't do what you want because it prints a reference to the object, and by the time you pop it open, it's changed. console.dir prints a directory of the properties in the object at the time you call it.
The JSON idea below is a good one; you could even go on to parse the JSON string and get a browsable object like what .dir() would give you:
console.log(JSON.parse(JSON.stringify(obj)));

Why reusing emptied array in Javascript not possible? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 7 years ago.
I programmed in a few programming languages, from time to time i have some experience also with Javescript.
Here my situation: I have an array as global variable (myArray). I need to refill myArray with data from the DB when some event happens. So I wrote myFunction, in which myArray is emptied to remove eventual older data, then filled again with the new data.
If I don't delete the array content, everything works, but (of course) the array may contain also older data and will grow each time the function is called, and I don't want that.
What I don't understand is the following:
If I delete the content of myArray when myFunction starts, I cannot refill it again...
Here the simplified version of my code, thanks everyone for any help:
myArray = []; // global variable
// IN MYFUNCTION
//first empty the array, then refill it with data from DB
{
// Let's empty myArray, tried all 4 different ways to do that -- no difference:
// Way 1)
//while(myArray.length > 0) { myArray.pop(); }
//OR Way 2)
//myArray.length=0;
//OR Way 3)
//myArray.splice(0,myArray.length);
//OR Way 4)
myArray = [];
dataNamesQuery = "SELECT something FROM db according user's input";
DatabaseInterface.get_data_now(dataNamesQuery).get({}, function(result){
allDataNames = result.Results;
for(i in allDataNames){
myArray.push(allDataNames[i].something);
}
});
}
//IF I DELETE THE CONTENT OF MYARRAY, THIS WILL PRINT NOTHING;
//ELSE IF I DON'T DELETE ITS CONTENT, THE ARRAY CONTAINS NEW AND OLD DATA
for(ix in myArray){
console.log("in myArray got " + myArray[ix]);
}
} //MYFUNCTION END
--edits--
I see that this question is marked as duplicated, maybe it is, just I couldn't find a question that suited to this situation.
I see from answers you listed that maybe the problem is in synchronization, so I have to learn about this topic

Previous console log change after assign new value in javascript sub object property. Help me [duplicate]

This question already has an answer here:
JavaScript logging object with mutating state [duplicate]
(1 answer)
Closed 8 years ago.
Recently I am facing problem with javascript sub object value assign. My sample code is
var user = {
name: {
fname: 'Apple'
}
};
console.log(user);
user.name.fname = 'Orange';
console.log(user);
So its console twice But, fname value always show Orange. But I want output will be Apple then Orange. How do i do that or actually what happened? Please Let me explain actually what going on.
Try this code:
var user = {
name: {
fname: 'Apple'
}
};
console.log(user.name.fname);
user.name.fname = 'Orange';
console.log(user.name.fname);
Cheers.
You can use console.dir(object) to print object
console.dir(user);
Don't need to use console.log(user.name.f);

Categories