Create JSON with data from database and JavaScript generated - javascript

I need to create a calendar view with fullcalendar.io. For some dates, I have a specific price in my database and I retrieve it, but for some dates (without specific prices) I need to put the usual rates in the objects I need to create with JavaScript. Problem is now because I don't know how to make JSON for that.
In short: I need to have a price for every date, but for some dates I get data from database. How do I create such JSON objects in JavaScript?
I have this code:
var db_data = [
{
"id": 5,
"user_id": 1,
"article_id": 5,
"title": "",
"start": "2016-03-25 15:18:46"
},
{
"id": 4,
"user_id": 1,
"article_id": 5,
"price": 55,
"title": "",
"start": "2016-03-15 15:18:46"
},
{
"id": 3,
"user_id": 1,
"article_id": 5,
"price": 35,
"title": "",
"start": "2016-03-07 15:18:46"
},
{
"id": 2,
"user_id": 1,
"article_id": 5,
"price": 22,
"title": "drugi",
"start": "2016-03-05 15:18:46"
},
{
"id": 1,
"user_id": 1,
"article_id": 5,
"price": 44,
"title": "prvi",
"start": "2016-02-04 15:18:46"
}
];
// declare variables
var period_start = new Date('2016-02-02'),
period_end = new Date('2016-03-03'),
current_date = period_start,
array_of_all_dates = [];
// Create a populated array of dates
// Create a populated array of dates
while (current_date.getTime() <= period_end.getTime()) {
array_of_all_dates.push(current_date);
current_date = new Date(+current_date);
current_date.setDate(current_date.getDate() + 1);
}
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
return new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime(); // You need to do this comparison better!
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
title: '',
start: date,
price: '{{$article->price}}'
};
console.log(new_object);
return new_object;
});
console.log('result'+array_of_all_dates);
drawCalendar(array_of_all_dates);
And with this code I get data from database and dates (start) which are not excist in database I create with JavaScript.
But with this function I get this data and I can't create calendar:
I also try with this:
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
var db_data_date = new Date(db_data.start.replace(" ", "T"));
return db_data_date.getFullYear() === date.getFullYear() &&
db_data_date.getMonth() === date.getMonth() &&
db_data_date.getDay() === date.getDay();
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
a_property: 'some_default_value',
start: date
};
console.log(new_object);
return new_object;
});
But currently I get this:

I don't see how this:
new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime()
can ever be true. The dates in db_data have a time set in them "2016-03-15 15:18:46", but the dates you create in array_of_all_dates do not Date('2016-02-02').
Your second date comparison seems to work, but I am unclear what it is you hope to be the result of the:
array_of_all_dates.map( ... );
In some case you return an element from db_data which looks like this:
{ "id": 5", "user_id": 1, "article_id": 5, "title": "", "start": "2016-03-25 15:18:46" }
and if there was no "match" you return an object that looks like this:
{ a_property: 'some_default_value', start: date }
Note that all the original elements of array_of_all_dates are replaced by this operation.
What is it that you want to end up in array_of_all_dates so you can pass it to drawCalendar?

Related

how can i get the "validade" value from the array and get only?

The array
{"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02-
01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade":"2026-06-
01","bandeira":"Mastercard"}]}
Inside digiAno I wanted to put only the year value of the array
this.dadosCC.reset({
'parcelas': '1',
'digiNumero': ['**** **** ****', cartao.mask] ,
'digiNome': cartao.holder,
'digiMes': '',
'digiAno': cartao.validade,
'valor': this.cartS.cart.valorTotal,
'cpfInput': this.userS.user.cpf,
'cardToken': this.cardToken,
'digiCVV':''
});
If you want to get the entire information of validade and put that information inside cartao use this code:
myObject: any = {
"status": true,
"data": [{
"id": 1,
"pessoa_id": 75505,
"created_at": "2022-02-01T17:42:46.000000Z",
"holder": "LEONARDO LIMA",
"validade": "2026-06-01",
"bandeira": "Mastercard"
}]
};
cartao: any = this.myObject.data[0].validade;
If you want to get year, month and the day use this.
myObject: any = {
"status": true,
"data": [{
"id": 1,
"pessoa_id": 75505,
"created_at": "2022-02-01T17:42:46.000000Z",
"holder": "LEONARDO LIMA",
"validade": "2026-06-01",
"bandeira": "Mastercard"
}]
};
cartao: any = this.myObject.data[0].validade;
dateArray: any = this.cartao.split('-');
year = this.dateArray[0];
month = this.dateArray[1];
day = this.dateArray[2];

How do I find the latest time for each date in a JSON array?

I have this array in JSON format:
var result=[
{
"index": 13,
"id": 1122,
*
The approach below:
get a unique list of only the dates from the array i.e. dd/mm/yyyy
for each date in the unique list, create a sorted array per the times for that date
return the 0th item from that sorted array for that date
Example code:
var result = [
{
"index": 13,
"id": 1122,
"price": 100,
"dateTime": "11/12/2020 1:59"
},
{
"index": 14,
"id": 1122,
"price": 300,
"dateTime": "11/12/2020 3:15"
},
{
"index": 15,
"id": 1122,
"price": 314,
"dateTime": "11/13/2020 2:20"
},
{
"index": 16,
"id": 1122,
"price": 280,
"dateTime": "11/13/2020 2:23"
}
];
// get a list of the dates in result
// nothing fancy - the date is just a key
var dates = result.map(k => k.dateTime.substr(0, 10));
// get unique dates from this array
var uniqueDates = Array.from(new Set(dates));
// for each unique date, sort the times descending
// return the first item (latest) for that date
var filtered = uniqueDates.map(ud => {
var dateItems = result.filter(d => d.dateTime.substr(0, 10) == ud);
dateItems.sort((a, b) => (new Date(b.dateTime)).getTime() - (new Date(a.dateTime)).getTime());
return dateItems[0];
});
// output
console.log(filtered);
Sorting the Array on the Date value of dateTime, write a result array with dates-only as keys, retrieve the values of the result.
The TypeError, by the way, is because you should check for i + 1 being smaller than result.length in the loop (this will be falsy for the last element within the loop. In that case new Date(result[i+1].dateTime) will throw the error).
// initialize log helper
const log = Logger();
// create an empty Object
const result = {};
// sort data ascending
const dataSorted = getData().sort((a, b) =>
new Date(a.dateTime) - new Date(b.dateTime));
// add to result with datestring as key.
// The value with the most recent date will be preserved
// because key values are unique (so equal keys are overwritten)
dataSorted.forEach(v => result[new Date(v.dateTime).toDateString()] = v);
// the values of [result] contain the most recent records per date
log(Object.values(result));
// this can also be a one liner, using a reducer method
const resultX = Object.values(
getData()
.sort( (a, b) => new Date(a.dateTime) - new Date(b.dateTime) )
.reduce( (acc, value) =>
({...acc, [new Date(value.dateTime).toDateString()]: value}), {} )
);
log(`\n**from reducer`, resultX);
function getData() {
return [{
"index": 13,
"id": 1122,
"price": 100,
"dateTime": "11/12/2020 1:59"
},
{
"index": 14,
"id": 1122,
"price": 300,
"dateTime": "11/12/2020 3:15"
},
{
"index": 15,
"id": 1122,
"price": 314,
"dateTime": "11/13/2020 2:20"
},
{
"index": 16,
"id": 1122,
"price": 280,
"dateTime": "11/13/2020 2:23"
}
];
}
function Logger() {
const report = document.querySelector("#report") ||
document.body.insertAdjacentElement(
"beforeend",
Object.assign(document.createElement("pre"), {id: "report"}));
return (...args) => args.forEach(stuff =>
report.textContent += (stuff instanceof Object
? JSON.stringify(stuff, null, 2) : stuff) + "\n");
}
You can group the data based on date like,
const groups = data.reduce((groups, currVal) => {
const date = currVal.dateTime.split(' ')[0];
if (!groups[date]) {
groups[date] = [];
}
groups[date].push(currVal);
return groups;
}, {});
-> Here we split the date and and time part using split(' ') and took the date alone separately and form a group,
const date = currVal.dateTime.split(' ')[0];
And then you can get the recent date and time using the method,
groups[item].reduce((a, b) => (a.dateTime > b.dateTime ? a : b));
Working snippet:
const data = [
{
"index": 13,
"id": 1122,
"price": 100,
"dateTime": "11/12/2020 1:59"
},
{
"index": 14,
"id": 1122,
"price": 300,
"dateTime": "11/12/2020 3:15"
},
{
"index": 15,
"id": 1122,
"price": 314,
"dateTime": "11/13/2020 2:20"
},
{
"index": 16,
"id": 1122,
"price": 280,
"dateTime": "11/13/2020 2:23"
}
];
//Group the data based on date
const groups = data.reduce((groups, currVal) => {
const date = currVal.dateTime.split(' ')[0];
if (!groups[date]) {
groups[date] = [];
}
groups[date].push(currVal);
return groups;
}, {});
//Get the recent date and time based on each group
const result = [];
Object.keys(groups).filter(item => {
const newData = groups[item].reduce((a, b) => (a.dateTime > b.dateTime ? a : b));
result.push(newData);
});
console.log(result)

Return all values as an array after the map function

I want to write to the array the value of each sum of all the reports.
month: donate_report.report[0].reports[0].sum
Unfortunately, this function returns an empty array:
month: donate_report.report[0].reports;
const doubles = month.map(function (elem) {
return elem.sum;
});
Could you please tell me what am I doing wrong? thanks in advance
"reports": [
{
"id": 1,
"sum": 5221,
},
{
"id": 2,
"sum": 5421,
}
]
The data structure you provided was not complete or wrong. Considering it as a object you can use map and return the sum property
var a={"reports": [
{
"id": 1,
"sum": 5221,
},
{
"id": 2,
"sum": 5421,
}
]}
const doubles=a.reports.map((e)=>e.sum);
console.log(doubles)

How do I create a new object from an existing object in Javascript?

Working on JavaScript app and need help in creating a new object from response received from ajax call.
The output received is array of objects, sample format below:
{
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to swim",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
]
}
However, my component expects JS Object in the following format:
{
id: "e1",
title: "Express",
start: "Jan 13, 2010",
description: "Jan 13, 2010"
}
Is following approach correct, please suggest better approach if any
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
}
};
var gcalEvents = {};
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
console.log(content.items.length);
for (var index = 0; index < content.items.length; index++) {
var obj = content.items;
console.log(obj);
jsonObj.id = obj[index]["id"];
jsonObj.title = obj[index].summary;
jsonObj.start = obj[index].start.dateTime;
jsonObj.description = "";
console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);
You could take a more functional approach with the following:
var parsed = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: item.start.dateTime
}
})
This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects.
Take a look at this fuller example.
I have another way to convert this content.
Using Underscore.js to make the code more readable.
Here is the example:
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}, {
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}]
};
var result = _.map(content.items, function(item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
The result as following:
[
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"title": "Learn to code",
"start": "2017-03-04T19:00:00+05:30",
"description": ""
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"title": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": "2017-03-07T11:30:00+05:30",
"description": ""
}
]
At the core, you are trying to 'map' from one set of data to another. Javascript's mapping function of array should be sufficient. Eg.
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}]
};
var results = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(results);
var jsonObj=[];
for (var index = 0; index < content.items.length; index++) {
var obj = {};
console.log(obj);
obj["id"]=content.items[index].id;
obj["title"]=content.items[index].summary;
obj["start"]=content.items[index].start.dateTime;
obj["description"]="";
jsonObj.push(obj);
console.log(jsonObj);
//gcalEvents[index] = jsonObj;
}
This will give you jsonObj as your desired json object.
Hope this helps :)
Here's the fixed code:
One error was when you've listed the content items, a "]" was missing at the end.
The second one was that you were trying to assign a values to an undefined object, you first need to define the object eg: jsonObj = {}; and then do the assigning of values.
I've preferred to do the object define and assigning of the values in one go.
In order to have the output as an array, you just have to define the colection as an array and not am object eg: var gcalEvents = []
var content = {
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}
]
};
var gcalEvents = [];
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
//console.log(content.items.length);
for(var index=0; index < content.items.length; index++){
var obj = content.items[index];
//console.log(obj);
jsonObj = {
'id': obj["id"],
'title': obj.summary,
'start': obj.start.dateTime,
'description': ""
}
//console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);

Find is date between array of start and end dates

I have a array of objects containing dates, if a user added another start and end date it cannot overlap with any existing dates in the array.
Using Moment I have this loop but no alert is fired when I input a date that overlaps
Using the input dates, startDate: "2013-09-02T00:00:00", endDate: "2015-05-05T00:00:0, the loop over the last array item should fire the alert, as the dates overlap.
let resultData = data.row;
let array = this.props.sectionData;
let inputStartDate = Moment(resultData.startDate, "DD/MM/YYYY");
let inputEndDate = Moment(resultData.endDate, "DD/MM/YYYY");
array.forEach( function (i) {
if(i.startDate && i.endDate) {
let startDate = Moment(i.startDate, "DD/MM/YYYY");
let endDate = Moment(i.endDate, "DD/MM/YYYY");
if (inputStartDate.isBetween(startDate, endDate) || inputEndDate.isBetween(startDate, endDate)) {
alert('date range cannot overlap');
}
}
});
My data:
[
{"id": 3,
"startDate": 2013-09-01T00:00:00,
"endDate": 2013-09-01T00:00:00,
"description": null,
"userId": 900,
"userName": "",
"documents": [],
},
{
"id": 5,
"startDate": 2013-09-01T00:00:00,
"endDate": 2013-09-01T00:00:00,
"description": null,
"userId": 1,
"userName": "",
"documents": [],
"contributors": []
},
{
"id": 6,
"startDate": "2013-09-01T00:00:00",
"endDate": "2014-08-31T00:00:00",
"description": "content",
"userId": 1,
"userName": ""
},
Let moment parse the object. See https://plnkr.co/edit/OqKNDsSWvcMc3PXOcu9F?p=preview for a working example.
Explanation:
let inputStartDate = moment("2013-09-02T00:00:00");
let inputEndDate = moment("2015-05-05T00:00:00");
As ADyson explained your were passing in the incorrect formats. Also you are missing quotes in your test data around your dates for ids 3 and 5.

Categories

Resources