let startDate = moment('2016-01-01');
let endDate = moment('2016-01-12');
for (let m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
let queryDate = m.format('DD MMM YYYY');
console.log(queryDate);
queries.push(function (callback) {
processMeterreadings("{ 'params': { 'path': { 'mpan': '2198765119780' },'querystring': {'startdate': '" + queryDate.toString() + " 00:00','enddate': '" + queryDate.toString() + " 23:30','readtype': 'all'}}}",callback);
}
);
}
queries.forEach(function(data){
console.log(data.toString());
})
The values being returned for the last foreach are all the same
function (callback) {
processMeterreadings("{ 'params': { 'path': { 'mpan': '2198765119780' },'querystring': {'startdate': '" + queryDate.toString() + " 00:00','enddate': '" + queryDate.toString() + " 23:30','readtype': 'all'}}}",callback);
}
i would expect the value of the date to be in the item in the array not the variable name.
How do i change it so the item in the array has 2016-01-02 in place of queryDate.toString()?
You are pushing functions into the array, but those functions are never executed. In order to evaluate the string concatenation in the function body, the functions must actually be executed.
Considering building the string outside of the function where the code actually executes, as opposed to pushing the unexecuted code into your array.
You can also build an object literal and use JSON.stringify to handle turning it into JSON for you:
let startDate = moment('2016-01-01');
let endDate = moment('2016-01-12');
for (let m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
let queryDate = m.format('DD MMM YYYY');
console.log(queryDate);
let json = JSON.stringify({
params: {
path: {
mpan: '2198765119780'
},
querystring: {
startdate: queryDate.toString() + ' 00:00',
enddate: queryDate.toString() + ' 23:30',
readtype: 'all'
}
}
})
queries.push(function (callback) {
processMeterreadings(json)
});
}
Alternatively (and preferably), don't build the JSON so early. Just store the date ranges in your array, and iterate over them when you're actually ready to perform the query:
let startDate = moment('2016-01-01');
let endDate = moment('2016-01-12');
for (let m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
let queryDate = m.format('DD MMM YYYY');
queries.push(queryDate);
}
queries.forEach(function(queryDate) {
processMeterreadings(JSON.stringify({
params: {
path: {
mpan: '2198765119780'
},
querystring: {
startdate: queryDate.toString() + ' 00:00',
enddate: queryDate.toString() + ' 23:30',
readtype: 'all'
}
}
}));
});
Related
REACT NATIVE CODE
constructor(props) {
super(props);
this.state = {
day: '',
month: '',
year: '',
asked_dat: '',
asked_clas: 'CLASS',
asked_su: 'SUBJECT'
};
}
set_date = () => {
this.setState({
asked_dat: this.state.day + '-' + this.state.month + '-' + this.state.year
});
};
retrieve_data = () => {
var asked_date = this.state.asked_dat;
var asked_class = this.state.asked_clas + '/';
var asked_sub = this.state.asked_su;
var date_class = asked_date + '/' + asked_class;
var sub_roll = asked_sub + '/' + 'PRESENT_ROLL_NO';
console.log(date_class + sub_roll);
db.ref(date_class).once('value', function(snapshot) {
console.log(snapshot.child(sub_roll).val());
});
};
when i assign an array variable like
temp_arr = snapshot.child(sub_roll).val();
it returns empty array but if console log it i get the array,
please help.
If you are assigning an array variable to the result outside the value event then it will return empty since once() is asynchronous which means it will not wait until the data is retrieved, therefore if you do this:
db.ref(date_class).once('value', function(snapshot) {
console.log(snapshot.child(sub_roll).val());
});
temp_arr = snapshot.child(sub_roll).val();
};
temp_arr will return an empty array. You need to do the following:
db.ref(date_class).once('value', function(snapshot) {
temp_arr = snapshot.child(sub_roll).val();
console.log(temp_arr);
});
};
To access it outside the value event do the following:
retrieve_data = () => {
return new Promise((resolve, reject) => {
var asked_date = this.state.asked_dat;
var asked_class = this.state.asked_clas + '/';
var asked_sub = this.state.asked_su;
var date_class = asked_date + '/' + asked_class;
var sub_roll = asked_sub + '/' + 'PRESENT_ROLL_NO';
console.log(date_class + sub_roll);
db.ref(date_class).once('value', function(snapshot) {
temp_arr = snapshot.child(sub_roll).val();
resolve(temp_arr);
});
});
};
Then when calling the function do the following:
retrieve_data().then((value) => {
console.log(value); //returns array
});
I have two references in firebase :
1. products
2. nutritions
Scenario is when user complete a list of choices, their nutrition values inside nutritions(2) reference should be picked from the product catalogue maintained under products reference(1)
Here is the code I am trying to work with but not sure what I am missing, Below code only update first product nutrition content. I am new with Angular2 and firebase.
//capturing promises
let promises = Object.keys(choices)
.map(k => {
return new Promise((resolve, reject) => {
this.updateNutrtion(choices[k].choice,resolve,reject);
});
});
//promise.all
Promise.all(promises).then((object)=> console.log(object));
updateNutrtion(choice,res,rej){
//logic to get the nutritions
return new Promise((res,rej)=>{
firebase.database().ref('/products/' + choice).once('value',function(snapshot){
snapshot.forEach(function(child){
var consumeDay;
var today = new Date().toISOString();
var year = today.split("-")[0];
var month = today.split("-")[1];
var day = ( today.split("-")[2] ).split("T")[0]
consumeDay = day + '-' + month + '-' + year;
// update firebase nutrition
firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + child.ref.key).once('value',function(nutrition){
firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + child.ref.key).update({
unit : child.val().unit,
value : (nutrition.val()!=null) ? (nutrition.val().value + child.val().value) : (child.val().value)
})
})
return false;
})
}).then((key)=>{
res(key);
});
})
}
Please assist where I am going wrong.
solved it.. In case if this help someone else , posting code below.
//handelling promises over an array
let promises = Object.keys(choices)
.map(k => {
var val =this.updateAllNutritions(choices[k].choice)
.then(function(values) {
var consumeDay;
var today = new Date().toISOString();
var year = today.split("-")[0];
var month = today.split("-")[1];
var day = ( today.split("-")[2] ).split("T")[0]
consumeDay = day + '-' + month + '-' + year;
// console.log('all done', values); // [snap, snap, snap]
Object.keys(values)
.map(j=>{
var unit = firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + values[j].valueOf).child('unit')
var value = firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + values[j].valueOf).child('value')
unit.transaction(function(currentUnit){
return values[j].unit;
});
value.transaction(function(currentValue){
return currentValue + values[j].value;
})
})
});
});
//update nutritions async function
updateAllNutritions(choice){
return firebase.database().ref('/products/' + choice).once('value').then(function(snapshot){
var nutritions = [];
var consumeDay;
var today = new Date().toISOString();
var year = today.split("-")[0];
var month = today.split("-")[1];
var day = ( today.split("-")[2] ).split("T")[0]
consumeDay = day + '-' + month + '-' + year;
snapshot.forEach(function(childSnapshot){
var promise = firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + childSnapshot.ref.key).once('value').then(function(snap){
var snapNull = null;
if(snap.val()!=null){
// console.log("currentvalue" + snap.val().value);
snapNull = snap.val().value
}
let promisedettrue = {
unit : childSnapshot.val().unit,
value : childSnapshot.val().value,
valueOf : childSnapshot.ref.key,
isNodenull : false,
currentValue : snapNull
};
let promisedetfalse = {
unit : childSnapshot.val().unit,
value : childSnapshot.val().value,
valueOf : childSnapshot.ref.key,
isNodenull : true,
};
if(snap.val()==null){
return promisedetfalse;
}else{
return promisedettrue;
}
},function(error){
// The Promise was rejected.
console.error(error);
});
nutritions.push(promise);
});
return Promise.all(nutritions);
},function(error){
// The Promise was rejected.
console.error(error);
})
}
I have an array and inside each array is a json object with each day of the week, so my array would look something like this:
var array = [
{
"wednesday":{
"notes":"some notes for Wednesday"
},
},
{
"thursday":{
"notes":"some notes for Thursday"
}
}
];
i can get away with updating my object directly by calling the following:
array[0].wednesday.notes = "updating Wednesday notes";
However, I need to update it dynamically....
I have a function that looks something like this, I need to dynamically call the day of the week on my json object and not be locked into just wednesday, i need to be able to call wednesday, thursday, friday etc on my object, how can i do this?
function updateObject(index, empNum) {
console.log(index+", "+empNum)
array[index].employee = $("#employee_" + empNum).val();
array[index].wednesday.notes = $("#employee_" + empNum + "_wed_notes").val();
array[index].wednesday.start = $("#employee_" + empNum + "_wed_shift_start").val();
array[index].wednesday.lunch = $("#employee_" + empNum + "_wed_lunch").val();
array[index].wednesday.end = $("#employee_" + empNum + "_wed_shift_end").val();
array[index].wednesday.short_day = $("#employee_" + empNum + "_wed_short_day").is(':checked');
array[index].wednesday.lack_of_work = $("#employee_" + empNum + "_wed_lack_of_work").is(':checked');
array[index].wednesday.full_day = $("#employee_" + empNum + "_wed_full_day").is(':checked');
var row_count = $("input[id*='employee_" + empNum + "_wed_job_']").length;
for (var i = 0; i < row_count; i++) {
var data = {};
data.job = $("input[id*='employee_" + empNum + "_wed_job_']").eq(i).val();
data.hrs = $("input[id*='employee_" + empNum + "_wed_hrs_']").eq(i).val();
data.cost_code = $("input[id*='employee_" + empNum + "_wed_cost_code_']").eq(i).val();
data.st = $("input[id*='employee_" + empNum + "_wed_st_']").eq(i).is(':checked');
data.ot = $("input[id*='employee_" + empNum + "_wed_ot_']").eq(i).is(':checked');
data.dt = $("input[id*='employee_" + empNum + "_wed_dt_']").eq(i).is(':checked');
array[index].wednesday.data[i] = data;
}
}
i tried something like doing
array[index].[thursday].notes = "x";
but unfortunately that doesnt work, i need to be able to call the day of the week i need when i call the function
so i need it to be something like updateObject(2,1,"thursday");
You just need to use the bracket notation to access the correct element in your array/objects.
This function would let you enter the week number (array index) as well as the day you want to update.
var array = [
{
"wednesday":{
"notes":"some notes for Wednesday"
},
},
{
"thursday":{
"notes":"some notes for Thursday"
}
}
];
function updateArray(index, day, newNotes) {
array[index][day].notes = newNotes;
}
console.log('before', array);
updateArray(1, 'thursday', 'updated notes');
console.log('after', array);
You can access all your data as so:
const updateObject = (index, empNum) => {
const i = array[index], k = Object.keys(i)[0]
if (!k) {return console.error("Invalid Data at index",index)}
i[k].notes = `Whatever you want with ${empNum}`
}
The function isolates the key given at a certain location and accesses it.
Example: updateObject(0, "15 employees")
If you would rather have ^^ do it by day then your function would look like:
const updateObject = (day, empNum) => {
const i = array.map(r => {
const k = Object.keys(r)[0];if (!k) {return false}
return r[k]
}).filter(r => r)[0]
if (!i) {return console.error("Invalid Day [%s] provided",day)}
i.notes = `Whatever you want with ${empNum}`
}
Not you can use it like: updateObject('tuesday', "15 employees")
We are using the glDatePicker plugin for our calendar event. But when 2 diffrent data on the same event occurs it only shows the last added. Is there a way to loop al items on the selected date? Could not find any input on looping this elements, console.log only shows the last input on date.
We need all data objects on given date, this can be multiple information on given date.
var all_dates = [];
$.each(agenda_json,function(index,value){
var date_split = value.calendar.split("-");
var date_event = {
year: date_split[0],
month: date_split[1],
day: date_split[2]
};
var new_event = {
date: new Date(date_event.year, (date_event.month - 1), date_event.day),
data: {
message: value.post_title,
onderwerp: value.onderwerp,
link: value.post_link
},
cssClass: value.weekday + ' event_day',
repeatMonth: false
};
all_dates.push(new_event);
});
$('#container_calendar').glDatePicker({
cssName: 'flatwhite',
showAlways: true,
specialDates: all_dates,
onClick: function(target, cell, date, data) {
target.val(date.getFullYear() + ' - ' +
date.getMonth() + ' - ' +
date.getDate());
if(data != null) {
$('#title_input').html(data.message);
$('.link_input').attr('href',data.link);
if(data.onderwerp == '' || data.onderwerp == " "){
$('#onderwerp_input').hide();
}else{
$('#onderwerp_input').show();
$('#onderwerp_input').html('<span>Onderwerp:</span><span>'+data.onderwerp+'</span>');
}
}
},
newcallback: function(){
$('body').find(".event_day").eq(0).trigger( "click" );
}
});
I have following array, there are some fields like dateofbirth in which I need to remove the time and change the format to MM-DD-YYYY.
var records = [
{
"recordno":"000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000063",
},
{
"recordno":"000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000067",
},
];
How to convert date format in an array for all fields which have Date type as data type?
Are the dates in your array date objects? Do you want to convert them to strings? Then maybe this will work.
for (var i = 0; i < records.length; ++i) {
var birthDate = new Date(records[i].dateofbirth);
var newBirthDateString = ('0' + birthDate.getDate()).slice(-2) + '-'
+ ('0' + (birthDate.getMonth()+1)).slice(-2) + '-'
+ birthDate.getFullYear();
records[i].dateofbirth = newBirthDateString;
if (records[i].dateofdeath !== null) {
var deathDate = new Date(records[i].dateofdeath);
var newDeathDateString = ('0' + deathDate.getDate()).slice(-2) + '-'
+ ('0' + (deathDate.getMonth()+1)).slice(-2) + '-'
+ deathDate.getFullYear();
records[i].dateofdeath = newDeathDateString;
}
}
Please check the below code. Hope this help you!
var records = [
{
"recordno":"RF-000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000063",
},
{
"recordno":"RF-000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000067",
},
];
for(var i=0;i<records.length;i++){
if(records[i].dateofbirth){
var splitDateTime = records[i].dateofbirth.split("T");
var splitDate = splitDateTime[0].split("-");
records[i].dateofbirth = splitDate[1] +"-"+ splitDate[2] +"-"+ splitDate[0];
}
}
JSFiddle URL: http://jsfiddle.net/mail2asik/YdBCq/1/
Updated:
It converts based on date field. Hope this help you!
for(var i=0;i<records.length;i++){
for( var attrName in records[i]){
if(records[i][attrName].indexOf("T") == 10){
var splitDateTime = records[i][attrName].split("T");
var splitDate = splitDateTime[0].split("-");
records[i][attrName] = splitDate[1] +"-"+ splitDate[2] +"-"+ splitDate[0];
}
}
}
JSFiddle URL: http://jsfiddle.net/mail2asik/YdBCq/3/