I have this script that takes data from a JSON with almost 100 data, then uses this data to bring the weather from an API and after that, inserts this data into an object (using a for for creating my 100 objects), I would like to add the objects that have a temperature > 99 in one array and the ones that have a temperature < 99 into another I have tried this way but doesn't seem to work, sorry if it's a super fool mistake that I can't see, thanks for your help!
This is my script:
async function calcWeather(){
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
for (var i in info) {
const _idOficina = info[i][0].IdOficina
const _nombreOficina = info[i][0].NombreOficinaSN
const _zona = info[i][0].Zona
const _estado = info[i][0].NombreEstado
const lat = info[i][0].latjson
const long = info[i][0].lonjson
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`
fetch(base)
.then((responses) => {
return responses.json()
})
.then((data) => {
// console.log(data)
var myObject = {
Id_Oficina: _idOficina,
Latitud: data.coord.lat,
Longitud: data.coord.lon,
Ciudad: data.name,
Estado: _estado,
Zona: _zona,
Nombre_Oficina: _nombreOficina,
Temperatura: data.main.temp,
Descripcion: data.weather[0].description
};
// validation
if (myObject.Temperatura < 99){
var lstValid = [];
function pushValid(){
lstValid.push(myObject[i]);
}
pushValid();
console.log(pushValid())
}
});
}
};
Your array is local, so for every object you create new lstValid array with no previous data. The solution is to create the array before fetching the data or before the loop:
async function calcWeather(){
var lstValid = []; // HERE
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
var lstValid = []; // OR HERE (ONLY ONE OF THEM)
for (...) {
...
}
You'll probably be best served by creating the array outside of that call since you're clearing it every run. Then simply add your object. Like Trincot's comment, i'm not sure what exactly you're indexing.
async function calcWeather(){
var lstValid = [];
....
if (myObject.Temperatura < 99){
lstValid[someindex] = myObject;
}
else{
lstNotValid[someOtherIndex] = myObject;
}
}
Related
I'm using parse with javascript (vueJs) and i'm experiencing the following issue : when I destroy an object and then get all my data, the object is still in the result. However, if I look in my parse backend, the object has been deleted.
This is my code:
methods: {
getNotes: async function() {
console.log("\nGETTING ALL NOTES")
const Object = Parse.Object.extend("notes");
const query = new Parse.Query(Object);
query.equalTo("user", Parse.User.current());
query.descending("createdAt");
const results = await query.find();
for (let i = 0; i < results.length; i++) {
var temp = {}
const object = results[i];
temp.id = object.id
temp.note = object.get('note')
temp.date = object.get('createdAt')
this.notes.push(temp)
}
},
deleteNote: async function() {
const Object = Parse.Object.extend("notes");
const query = new Parse.Query(Object);
query.equalTo("objectId", this.selectedItem);
const results = await query.first();
if (results){
await results.destroy() // I wait for the object to be destroyed
await this.getNotes() //Then, I call (again) my function to get all notes ... but it still contains the deleted object !!
}else{
alert("There was a problem with the query")
}
}
}
Any ideas why this happens and how can I "check" when my parse database is up to date so that I can get the data again (without the removed object) ?
// how I get the data
db.collection('Pins').get().then(snapshot => {
snapshot.forEach(pinInfo => {
pinsToMap(pinInfo)
});
});
// trying to set the data
function pinsToMap(pinInfo){
let pinName;
let pinCoOrdsLat;
let pinCoOrdsLong;
let pinToMapInfo;
pinName = doc.data().name
pinCoOrds = doc.data().coOrds
pinToMapInfo = doc.data().Info
Pins.child(Pins.coOrds).set({
coOrds: {
0:this = pinCoOrdsLat,
1:this = pinCoOrdsLong,
}
});
}
I am storing data in my database based off a map pin, I am now trying to use the stored data to create a pin on the map of the same place, how do I query out the coOrds in to pinCoOrdsLat / pinCoOrdsLong as this way doesn't seem to be working
If I correctly understand you question, the following should do the trick:
db.collection('Pins').get().then(snapshot => {
snapshot.forEach(pinInfo => {
pinsToMap(pinInfo)
});
});
// trying to set the data
function pinsToMap(pinInfo) { // IMPORTANT! => pinInfo is a DocumentSnapshot
const pinName = pinInfo.data().name
const pinCoOrds = pinInfo.data().coOrds
const pinToMapInfo = pinInfo.data().Info
//pinCoOrds is a JavaScript Array with two elements
const pinCoOrdsLat = pinCoOrds[0];
const pinCoOrdsLong = pinCoOrds[1];
//Use pinCoOrdsLat and pinCoOrdsLong the way you want, e.g. calling a leaflet method
}
You'll find here the doc for a DocumentSnapshot
My Firebase data base contains JSON objects, each with the same parameters as seen below. Firebase data
I want to get an array that has each objects country. So if I have 4,000 objects I want to get an array of 4,000 strings all containing a country.
Right now I can get the console to log all the 4,000 objects into an array using the code below.
componentWillMount() {
this.fetchData();
}
fetchData = async () => {
var data1 = [];
var fireBaseResponse = firebase.database().ref();
fireBaseResponse.once('value').then(snapshot => {
snapshot.forEach(item => {
var temp = item.val();
data1.push(temp);
return false;
});
console.log(data1);
});
}
But when I try doing
var fireBaseResponse = firebase.database().ref().child('country');
I get an array of nothing.
Any help would be great.
As mentioned in the comments, you can create a new temp object containing just country before pushing it into your array.
snapshot.forEach(item => {
var temp = { country: item.val().country };
data1.push(temp);
return false;
});
I'm trying to improve a firestore get function, I have something like:
return admin.firestore().collection("submissions").get().then(
async (x) => {
var toRet: any = [];
for (var i = 0; i < 10; i++) {
try {
var hasMedia = x.docs[i].data()['mediaRef'];
if (hasMedia != null) {
var docData = (await x.docs[i].data()) as MediaSubmission;
let submission: MediaSubmission = new MediaSubmission();
submission.author = x.docs[i].data()['author'];
submission.description = x.docs[i].data()['description'];
var mediaRef = await admin.firestore().doc(docData.mediaRef).get();
submission.media = mediaRef.data() as MediaData;
toRet.push(submission);
}
}
catch (e) {
console.log("ERROR GETTIGN MEDIA: " + e);
}
}
return res.status(200).send(toRet);
});
The first get is fine but the performance is worst on the line:
var mediaRef = await admin.firestore().doc(docData.mediaRef).get();
I think this is because the call is not batched.
Would it be possible to do a batch get on an array of mediaRefs to improve performance?
Essentially I have a collection of documents which have foreign references stored by a string pointing to the path in a separate collection and getting those references has been proven to be slow.
What about this? I did some refactoring to use more await/async code, hopefully my comments are helpful.
The main idea is to use Promise.all and await all the mediaRefs retrieval
async function test(req, res) {
// get all docs
const { docs } = await admin
.firestore()
.collection('submissions')
.get();
// get data property only of docs with mediaRef
const datas = await Promise.all(
docs.map(doc => doc.data()).filter(data => data.mediaRef),
);
// get all media in one batch - this is the important change
const mediaRefs = await Promise.all(
datas.map(({ mediaRef }) =>
admin
.firestore()
.doc(mediaRef)
.get(),
),
);
// create return object
const toRet = datas.map((data: MediaSubmission, i) => {
const submission = new MediaSubmission();
submission.author = data.author;
submission.description = data.description;
submission.media = mediaRefs[i].data() as MediaData;
return submission;
});
return res.status(200).send(toRet);
}
I need to create a new array from iterating mongodb result. This is my code.
const result = await this.collection.find({
referenceIds: {
$in: [referenceId]
}
});
var profiles = [];
result.forEach(row => {
var profile = new HorseProfileModel(row);
profiles.push(profile);
console.log(profiles); //1st log
});
console.log(profiles); //2nd log
I can see update of profiles array in 1st log. But 2nd log print only empty array.
Why i couldn't push item to array?
Update
I think this is not related to promises. HorseProfileModel class is simply format the code.
const uuid = require("uuid");
class HorseProfileModel {
constructor(json, referenceId) {
this.id = json.id || uuid.v4();
this.referenceIds = json.referenceIds || [referenceId];
this.name = json.name;
this.nickName = json.nickName;
this.gender = json.gender;
this.yearOfBirth = json.yearOfBirth;
this.relations = json.relations;
this.location = json.location;
this.profilePicture = json.profilePicture;
this.horseCategory = json.horseCategory;
this.followers = json.followers || [];
}
}
module.exports = HorseProfileModel;
await this.collection.find(...)
that returns an array of the found data right? Nope, that would be to easy. find immeadiately returns a Cursor. Calling forEach onto that does not call the sync Array.forEach but rather Cursor.forEach which is async and weve got a race problem. The solution would be promisifying the cursor to its result:
const result = await this.collection.find(...).toArray();
Reference