Console.log this WIx Code function - javascript

How do i log this successfully please. When i print, it prints only the syntax and not the values. I would also want to display it as text.
$w("#datePicker1").onChange( (onChange, $w) => {
let chosenDate = new Date($w("#datePicker1").value);
let date1 =chosenDate.getDate();
return date1;
});
$w("#datePicker2").onChange( (onChange, $w) => {
let chosenDate = new Date($w("#datePicker2").value);
let date2 = chosenDate.getDate();
return date2;
});
//printing everthing instead of values
console.log($w("#datePicker1").onChange);
console.log($w("#datePicker2").onChange);

this is because you're printing the function's actual code, as described in Function.prototype.toString().
$('#some_input').onChange function is an event handler and returning the object of the triggered element (see WixCode DatePicker API Docs)
You didn't mentioned what you wish to do with the date value, so I'm guessing that you may be wanted to put it in your database to update a specific item (the current item the dataset points to). Assuming this is what you're trying to do, here is a code to help:
$w("#datePicker1").onChange((event, $w) => {
let date = event.target.value;
// maybe do some manipulation here on the saved value
$('#dataset1').setFieldValue('last_modified_date', date)
});
Hope this could help,
Cheers!

Related

How to assign new key name to an object in an array of data?

In a React project, I've certain number of records which also contain input fields like Date and Text components in a Grid. I'm processing the date and text values in save function. All the records are fetched from JSON data, while saving date values its assigned to new key object but new one isn't getting updated with the old one. I have seen many similar posts but, none useful. Please refer to the code below:
Following is the function where I'm extracting both text and date values
const updateGrid = (data) => {
if (Array.isArray(allData) && allData?.length > 0) {
const tempData = allData;
tempData.map(x=> {
if(data.id === x.id) {
x.name = data.textVal
}
// Here I'm assigning the 'Establish' value with 'est'
if(data.id === x.id) {
x['est'] = x['Establish']
x.Establish = data.dateVal
}
})
setDataAll(tempData)
}
console.log('tempdataNew', dataAll)
}
As you can see from above picture, we have two keys, 'est' and 'Establish', but, I need only 'Establish', also getting undefined on 'name' when changed date value and vice-versa. What could be the best optimal solution to tackle this issue?
Please refer to Codesandbox --> https://codesandbox.io/s/jovial-aryabhata-95o2sy?file=/src/Table.js

Vue JS - Loop through a computed property to display a list of years

I currently have the following code that lists a list of years. I feel that all this code may be very unnecessary and perhaps a computed property for validYears, would help me make this code more optimal and get rid of the unnecessary watchers. My issue is converting this to a computed property as I'm failing to grasp the correct logic to achieve this. I'd appreciate if someone can offer an example of how I can set a computed property for valid years and still return the same result.
onBeforeMount(calculateDateRange)
watch(() => props.earliestDate, (newValue, prevValue) => {
calculateDateRange();
});
// If there is a new value passed from the parent, the dropdown should display that new value.
watch(() => props.latestDate, (newValue, prevValue) => {
calculateDateRange()
});
const validYears = ref([])
function calculateDateRange () {
for(let year = props.latestDate; year >= props.earliestDate; year--){
validYears.value.push(year)
}
}
I didn't provide the rest of the code not to clutter the question, but as one can see in this component I have a set of props that determine the values in my for loop.
You could optimize it as follows :
const validYears = computed(()=>{
let _years=[]
for(let year = props.latestDate; year >= props.earliestDate; year--){
_years.push(year)
}
return _years;
})

Moment date is rolling back to previous month

I have a datetime coming from my api as 2018-09-01T00:00:00.000Z. This is frame.scandate.
I have another date which is generated within my program as 2018-09. This is just scandate. These could be for any year/month combo, I am just giving examples.
My code looks like
this.allStations.forEach(station => {
station.frames.forEach(frame => {
if(moment(frame.scandate).isSame(moment(scandate), 'month')){
total+=frame.framesTotal;
}
})
This will match the previous frame.scandate with the the current scandate.
This:
scandate = '2018-09';\
frame.scandate = '2018-09-01T00:00:00.000Z';
console.log(moment(scandate).format('YYYY-MM'));
console.log(moment(frame.scandate).format('YYYY-MM'));
will output this:
2018-09
2018-08
I fixed the problem by doing this:
this.allStations.forEach(station => {
station.frames.forEach(frame => {
if(moment(frame.scandate).add(1, 'minute').isSame(moment(scandate), 'month')){
total+=frame.framesTotal;
}
})
.add(1, 'minute') being the key change here.
Is this because the frame.scandate value has the 00:00:00Z time value? Any explanation would be greatly appreciated.
There's probably something going on with the timezones.
This script, ran in Spain
var moment = require('moment'); // This is because I've tested it in a nodejs environment
var scandate = '2018-09';
var result = moment(scandate);
console.log(moment(result).format('YYYY-MM-DD'))
Outputs 2018-09-01
We could get around this by initializing frame.scandate like so:
frame.scandate = moment.utc('2018-09-01T00:00:00.000Z');
With moment.utc() instead of just moment() the output expectations are met.

Return most recent time in series of creationTimes

Not entirely sure how I word the question but my problem is Im doing an api call that returns a bunch of messages that have a creation time, now what I want to do is only return the latest creationTime for the messages with the same date so say If I have 30 messages on the 15/03/2018 I want to grab the latest time, and discard the rest.. and do that for each set of messages with the same date
So what Ive done so far is..
using lodash I have gotten all the messages, filtered out all the ones with a certain type, and I have ordered them by creationTime so the latest being at the top and going down.. now my question is how can I then make an array of the latest times for each date??
this._activityServiceProxy.getAllItems(start, end).subscribe(result => {
// this.messages = result;
// console.log(result);
let loginUnfiltered = _.filter(result, {'title': 'LOGIN'});
let loginFiltered = _.orderBy(loginUnfiltered, {'creationTime': 'desc'});
console.log(loginFiltered);
});
any help would be appreciated!
Thanks
Use .map(...) to get at array of only the latest creationTime:
this._activityServiceProxy.getAllItems(start, end).subscribe(result => {
// this.messages = result;
// console.log(result);
let loginUnfiltered = _.filter(result, {'title': 'LOGIN'});
let loginFiltered = _.orderBy(loginUnfiltered, {'creationTime': 'desc'});
const creationTimes = loginFiltered.map(l => l.creationTime);
console.log(creationTimes);
const latestTime = creationTimes[0];
console.log(latestTime);
});
You can use Underscore's groupBy function to achieve this:
const groups = _.groupBy(loginFiltered, (login) => {
const asDate = new Date(login.creationTime);
asDate.setHours(0, 0, 0, 0);
return asDate;
});
Object.keys(groups).forEach((key) => {
console.log(groups[key][0]);
});
You group by the creationDate property but remove the time component so all days get grouped together. You then loop through the result and just take the first entry per day.
Note that this assumes your creationTime property is a string, as it came from an API. If it's already a date, you don't need the new Date line.

how to print a javascript object's elements

i am new to javascript and i currently have an object printed to console when i use the following code:
clickEvents: {
click:function(target) {
console.log(target);
}
}
when i view console i can see the following object:
i am banging my head against a wall to write code that takes the object and prints it to a div using the .append() method. i am extermely new to working with javascript objects, and would appreciate any help trying to tease out an object and/or print the object data.
is events the object name? would i tease out the eventDate using something like events->eventDate?
I've made this over ~15 minutes so it's imperfect; there are types and edge cases surely unaccounted for and the design of the function could be better - not to mention that performing all of this as a giant string and then setting that as HTML is likely bad practice (I'm used to React now, ha!). Regardless, this will iterate over any array or object you pass to it and print it all in a big <ul> recursively.
const targetEl = document.querySelector('.js-target')
if (!targetEl) return
// Small helper functions
const isObj = data => typeof data === 'object' && !Array.isArray(data) && data !== null
const isArr = data => Array.isArray(data)
const dataToHTML = (data, noNode = false) => {
if (isObj(data)) {
const accumulator = Object.entries(data).reduce((acc, set) => acc + `<li><strong>${set[0]}</strong>: ${dataToHTML(set[1], true)}</li>`, '')
return `<ul>${accumulator}</ul>`
}
else if (isArr(data)) {
const accumulator = data.reduce((acc, item) => acc + dataToHTML(item), '')
return `<ul>${accumulator}</ul>`
}
else return noNode ? data : `<li>${data}</li>`
}
const logHTML = dataToHTML(exampleData)
targetEl.innerHTML = logHTML
Assuming that your data/variable is named exampleData.
Any questions pop them in the comments :-)
I'm not sure if you have a div that you want to append to already, but you would do something like this ->
document.getElementById("toBeAppendedTo").innerHTML = target.events[0].eventDate; where toBeAppendedTo is the id of the div you're trying to add this text to.
append() is a jquery function, not a javascript function.
That won't have any formatting and will just be the string value 07-28-2017 in a div.

Categories

Resources