I would like to format my JSON data to display Chart in my reporting templates.I want to produce a daily reporting chart with date wise Approved, Rejected and Pending data. My current JSON is:
json_data = '[
{"Approved":1,"updated_date":"2015-03-07"},
{"Approved":1,"updated_date":"2015-03-07"},
{"Rejected":1,"updated_date":"2015-03-07"},
{"Pending":1,"updated_date":"2015-03-07"},{"Approved":1,"updated_date":"2015-03-07"}
]';
I want to achieve this output
$data= '[
{
"date": "1 Mar",
"approved": 0,
"completed": 0,
"rejected": 0
},
{
"date": "2 Mar",
"approved": 0,
"completed": 0,
"rejected": 0
},
{
"date": "3 Mar",
"approved": 9,
"completed": 20,
"rejected": 11
},
{
"date": "4 Mar",
"approved": 20,
"completed": 50,
"rejected": 30
},
{
"date": "5 Mar",
"approved": 40,
"completed": 50,
"rejected": 10
},
{
"date": "6 Mar",
"approved": 35,
"completed": 70,
"rejected": 20
},
{
"date": "7 Mar",
"approved": 50,
"completed": 80,
"rejected": 30
}];'
I want to display only last 7 days data report through CHART.
You should first filter initial data by 'updated_date' (when the date is including in last 7 days), then group by 'updated_date' and then aggregate all desired properties by groups. Using underscore this will look something like this:
var json_data = '[{"Approved":1,"updated_date":"2015-03-07"}, {"Approved":1,"updated_date":"2015-03-07"}, {"Rejected":1,"updated_date":"2015-03-07"}, {"Pending":1,"updated_date":"2015-03-07"}, {"Approved":1,"updated_date":"2015-03-07"}, {"Approved":1, "Rejected": 1, "updated_date":"2015-03-08"}, {"Pending":17,"updated_date":"2015-03-02"} ]';
var json = JSON.parse(json_data);
var today = new Date('2015-03-10'); // new Date();
var sevenDays = 7 * 24 * 60 * 60 * 1000;
var result = _.map(_.groupBy(_.filter(json, function (item) {
var dateDiff = today.getTime() - new Date(item.updated_date).getTime();
return (dateDiff >= 0 && dateDiff < sevenDays);
}), 'updated_date'), function (g, key) {
var res = _.reduce(g, function (memo, item) {
return {
approved: memo.approved + (item.Approved | 0),
completed: memo.completed + (item.Completed | 0),
rejected: memo.rejected + (item.Rejected | 0),
pending: memo.pending + (item.Pending | 0),
};
}, { approved: 0, completed: 0, rejected: 0, pending: 0 });
res.date = key;
return res;
});
Here is a Live demo in JsFiddle
For the sake of readability please use the good old for loops.
P.S. beware of JavaScript dates and time zones if you're doing this on client side.
function sum(numbers) {
return _.reduce(numbers, function(result, current) {
if(_.isUndefined(current))
return result;
return result + parseFloat(current);
}, 0);
}
var result = _.chain(json_data)
.groupBy("updated_date")
.map(function(value, key) {
return {
updated_date: key,
Approved: sum(_.pluck(value, "Approved")),
Rejected: sum(_.pluck(value, "Rejected")),
Pending: sum(_.pluck(value, "Pending"))
}
})
.last(7)
.value();
console.log(JSON.stringify(result));
Related
Im trying to calculate the total subscription fee for the penalty jar at my workplace. Every month everyone pays a certain fee on top of their penalties. It started out being 20DKK and now it's 25DKK. I have the tdata in two json objects - one with persons and one with the subscription fees
It looks like this:
subscriptionFees = [
{
"id":2,
"date":"1900-01-01T00:00:00",
"amount":20.0
},
{
"id":1,
"date":"2018-05-01T00:00:00",
"amount":25.0
}
]
persons = [
{
"id":11,
"name":"Camilla",
"active":true,
"startDate":"2017-01-01",
"endDate":"1900-01-01"
},
{
"id":6,
"name":"Cathrine",
"active":true,
"startDate":"2019-03-01",
"endDate":"1900-01-01"
},
{
"id":1,
"name":"John",
"active":true,
"startDate":"2020-03-01",
"endDate":"2021-03-01"
}
]
I'm using jquery for most of my js functions. I imagine a function running through the persons-object and calculating the total subscription fee for each of them.
Maybe something like this:
$.each(persons, function (id, obj) {
totalSubscriptionfee = calculateSubscriptionfee(obj.startDate, obj.endDate);
})
function calculateSubscriptionfee(startDate, endDate){
???
}
Can someone help me with the calculateSubscriptionfee-function? The subscription fee might get changed again in the future, so the function needs to be able to adjust for that.
Thanks,
Peter
I may have made this too complicated, but wasn't sure how else to approach it. This will
first create a ranges array with start, end and amount using reduce
map the persons array, iterating through ranges to get the amount due from that range (if any)
get the total duration, in milliseconds, convert to a rough approximation of number of months, then round down using a modulus.
In the end you get a new persons array (npersons) with the total due in it.
const subscriptionFees = [{
"id": 2,
"date": "1900-01-01T00:00:00",
"amount": 20.0
},
{
"id": 1,
"date": "2018-05-01T00:00:00",
"amount": 25.0
}
]
const persons = [{
"id": 11,
"name": "Camilla",
"active": true,
"startDate": "2017-01-01",
"endDate": "1900-01-01"
},
{
"id": 6,
"name": "Cathrine",
"active": true,
"startDate": "2019-03-01",
"endDate": "1900-01-01"
},
{
"id": 1,
"name": "John",
"active": true,
"startDate": "2020-03-01",
"endDate": "2021-03-01"
}
]
let ranges = subscriptionFees.reduce((acc, a) => {
if (acc.length === 0 || Object.hasOwnProperty(acc[acc.length - 1].end)) {
let tmp = {
start: a.date,
amount: a.amount
};
acc.push(tmp)
} else {
acc[acc.length - 1].end = a.date;
acc.push({
start: a.date,
amount: a.amount
})
}
return acc;
}, [])
ranges[ranges.length - 1].end = new Date();
//console.log('ranges', ranges);
const npersons = persons.map(person => {
let ttl = 0;
// fix endDate
if (new Date(person.endDate).getTime() < new Date(person.startDate).getTime()) person.endDate = new Date();
// iterate ranges
ranges.forEach(a => {
let end = Math.min(new Date(a.end).getTime(), new Date(person.endDate).getTime())
let start = Math.max(new Date(a.start).getTime(), new Date(person.startDate).getTime())
// console.log('calculating', person.name, 'start', new Date(start), 'end', new Date(end));
let interval = end - start;
if (interval > 0){
let tmpttl = Math.floor( (interval / 1000 / 60 / 60 / 24 / 30) * +a.amount)
tmpttl -= tmpttl % a.amount
ttl += tmpttl;
}
})
person.total = ttl
return person
})
console.log(persons)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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)
I'm a newbie in Javascript and I'm trying to understand the destructuring approach also with object literals. So what I'm trying to do is to create a function which has two types of arguments: 1. It's a JSON data file which I want to iterate. 2. An object literal with a random value assigned. So I'm trying to iterate with this object value passed as a parameter and filter with the data from the JSON file with an if statement inside the array of objects iterator. And add to arr all the object which match.
Thanks everyone in advance.
Array of objects:
[
{ "id": 44, "hours": 100,"finished": false },
{ "id": 22, "hours": 80,"finished": false },
{ "id": 65, "hours": 34,"finished": false },
{ "id": 1098, "hours": 21,"finished": true },
{ "id": 2, "hours": 67,"finished": false },
{ "id": 765, "hours": 32,"finished": false },
{ "id": 223, "hours": 555,"finished": false },
{ "id": 986, "hours": 2,"finished": false }
]
main.js
const data = require('./example.json')
function dataFilter (items, {id: _id, hours: _hours, finished: _finished}) {
for (let i = 0; i < items.length; i++) {
let arr = [];
if (items[i].id === _id) {
arr.push(items[i])
}
else if (items[i].hours >= _hours){
arr.push(items[i])
}
else if (items[i].finished === finished){
arr.push(items[i])
}
return arr;
}
}
console.log(dataFilter(data,{ id: 65 }));
console.log(dataFilter(data,{ hours: 30 }));
You don't need destructuring, what you need is array filter.
You also forgot to set a default {} so you can access undefined keys:
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter
const data = [
{ "id": 44, "hours": 100,"finished": false },
{ "id": 22, "hours": 80,"finished": false },
{ "id": 65, "hours": 34,"finished": false },
{ "id": 1098, "hours": 21,"finished": true },
{ "id": 2, "hours": 67,"finished": false },
{ "id": 765, "hours": 32,"finished": false },
{ "id": 223, "hours": 555,"finished": false },
{ "id": 986, "hours": 2,"finished": false },
{ "id": 1986, "hours": 30,"finished": false },
];
function dataFilter (items, {id: _id, hours: _hours, finished: _finished} = {}) {
return items.filter((item) => item.id === _id || item.hours >= _hours || item.finished === _finished);
}
document.getElementById('results').innerHTML = `
<pre>
ID: 65
${JSON.stringify(dataFilter(data,{ id: 65 }), null, 2)}
HOURS: 30
${JSON.stringify(dataFilter(data,{ hours: 30 }), null, 2)}
</pre>
`
<div id="results"></div>
Approach with multiple filters
It is also possible to use more than one filter at once:
const data = [
{ "id": 44, "hours": 100,"finished": false },
{ "id": 22, "hours": 80,"finished": false },
{ "id": 65, "hours": 34,"finished": false },
{ "id": 1098, "hours": 21,"finished": true },
{ "id": 2, "hours": 67,"finished": false },
{ "id": 765, "hours": 32,"finished": false },
{ "id": 223, "hours": 555,"finished": false },
{ "id": 986, "hours": 2,"finished": false },
{ "id": 1986, "hours": 30,"finished": false },
];
function dataFilter (items, filters = {}) {
// this will create a list of function on the fly for every `filters` you pass.
const fnList = Object.keys(filters)
.map((key) => (list) => list.filter((item) => item[key] === filters[key]));
let res = [...items];
while (cursor = fnList.shift()) {
res = cursor(res);
}
return res;
}
document.getElementById('results').innerHTML = `
<pre>
ID: 44, HOURS: 100
${JSON.stringify(dataFilter(data,{ id: 44, hours: 100 }), null, 2)}
ID: 2, HOURS: 67
${JSON.stringify(dataFilter(data,{ id: 2 }), null, 2)}
</pre>
`
<div id="results"></div>
If you want to specify the operators used for the comparaison, use a fonction as explained here: Are Variable Operators Possible?
Looks like you want to be able to filter the data by any combination of the three items in that object.
function filterFactory({id, hours, finished}) {
return function filter(item) {
let isGoodValue = false;
if (id !== undefined && item.id === id) isGoodValue = true;
// for the second and third checks we'll short-circuit if it already
// passed an earlier check
if (!isGoodValue && hours !== undefined && item.hours >= hours) isGoodValue = true;
if (!isGoodValue && finished !== undefined && item.finished === finished) isGoodValue = true;
return isGoodValue;
};
}
data.filter(filterFactory({id: 2}));
Note that we're using the native filter method on arrays. filterFactory is a factory that makes callbacks to pass to filter based on one or more of the three factors you're filtering on.
The situation is: I have an array of objects, in which every object has an array of objects. The array looks like this:
[
{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511001,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511008,
"timezoneOffset": -60,
"year": 118
},
}
],
},
{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511011,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511028,
"timezoneOffset": -60,
"year": 118
},
}
],
}
]
So I want to sort the users, and the dislikes by the time in their dislikes. So the user with the earliest dislike would be first, as well as the earliest dislike would be first in each users' dislikes array. I believe I have to do multiple sorts, but how can I do that exactly?
You can map the items and add a property to it containing the earliest dislike and then sort on that:
const data = [{"dislikes":[{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511001,"timezoneOffset":-60,"year":118}},{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511008,"timezoneOffset":-60,"year":118}}]},{"dislikes":[{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511011,"timezoneOffset":-60,"year":118}},{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511028,"timezoneOffset":-60,"year":118}}]}];
console.log(
data
//map and add newestDislike property
.map((d) => ({
...d,
//reduce and only takes the lowest time value
newestDislike: (d.dislikes || []).reduce(
(result, item) =>
item.createDate.time < result
? item.createDate.time
: result,
Infinity, //defaults to infinity (if no dislikes)
),
}))
.sort((a, b) => a.newestDislike - b.newestDislike),
);
If the dislikes in the user are already sorted by oldest date first then you can skip the map and reduce part. If a user can have empty dislikes or undefined then make sure you use a getter function with a default so your code won't crash:
//gets a nested prop from object or returns defaultValue
const get = (o = {}, path, defaultValue) => {
const recur = (o, path, defaultValue) => {
if (o === undefined) return defaultValue;
if (path.length === 0) return o;
if (!(path[0] in o)) return defaultValue;
return recur(o[path[0]], path.slice(1), defaultValue);
};
return recur(o, path, defaultValue);
};
console.log(
data.sort(
(a, b) =>
get(
a,
['dislikes', 0, 'createDate', 'time'],
Infinity,
) -
get(
b,
['dislikes', 0, 'createDate', 'time'],
Infinity,
),
),
);
//Supply the array you've metioned as the argument users to the below method, sortDislikesForAllUsers
let sortDislikesForAllUsers = function(users) {
return users.map(user => {
return {
dislikes: user.dislikes.sort((dislikeA, dislikeB) => ((dislikeA.createDate.time < dislikeB.createDate.time) ? -1 : (dislikeA.createDate.time > dislikeB.createDate.time) ? 1 : 0))
}
})
}
//Supply the array returned in the above method as input to the below method, sortUsers
let sortUsers = function(arrayOfSortedDislikesPerUser) {
return arrayOfSortedDislikesPerUser.sort((userA, userB) => ((userA.dislikes[0].createDate.time < userB.dislikes[0].createDate.time) ? -1 : (userA.dislikes[0].createDate.time > userB.dislikes[0].createDate.time) ? 1 : 0))
}
let arrayOfSortedDislikesPerUser = sortDislikesForAllUsers(users);
let finalSortedArray = sortUsers(arrayOfSortedDislikesPerUser);
console.log(finalSortedArray);
In the below snippet,
sortDislikesForAllUsers This method sorts the dislikes for individual
users
sortUsers This method sorts the users based on the first dislike time
of the sorted dislikes array obtained from the above method
Simple :)
Run the below snippet. You can directly copy paste it in your code!
let users = [{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511001,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511008,
"timezoneOffset": -60,
"year": 118
},
}
],
},
{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511011,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511028,
"timezoneOffset": -60,
"year": 118
},
}
],
}]
let sortDislikesForAllUsers = function(users) {
return users.map(user => {
return {
dislikes: user.dislikes.sort((dislikeA, dislikeB) => ((dislikeA.createDate.time < dislikeB.createDate.time) ? -1 : (dislikeA.createDate.time > dislikeB.createDate.time) ? 1 : 0))
}
})
}
let sortUsers = function(arrayOfSortedDislikesPerUser) {
return arrayOfSortedDislikesPerUser.sort((userA, userB) => ((userA.dislikes[0].createDate.time < userB.dislikes[0].createDate.time) ? -1 : (userA.dislikes[0].createDate.time > userB.dislikes[0].createDate.time) ? 1 : 0))
}
let arrayOfSortedDislikesPerUser = sortDislikesForAllUsers(users);
let finalSortedArray = sortUsers(arrayOfSortedDislikesPerUser);
console.log(finalSortedArray);
EDIT: WRT to the comment by #HMR:
1. It mutates the original array. Yes. If you want to avoid mutation, you must create a copy of the sent array.
let noRefCopy = new Array()
noRefCopy = noRefCopy.concat(originalArr)
Now, perform sorting on the copy and return the same.
2. If you wanna have checks for undefined etc, sure you can.
The above answer attempts to address the logic. Sure we can address the above 2 concerns if the question is really specific to them.
Cheers,
Kruthika
Check the code below. This will let you sort based on time:
function sortByTime(obj1, obj2){
return obj1.time - obj2.time;
}
array.sort((obj1, obj2)=>{
obj1.dislikes.sort(sortByTime);
obj2.dislikes.sort(sortByTime);
return obj1.dislikes[0].time - obj2.dislikes[0].time;
});
I did not get what you meant by earliest time. The above code sorts time in ascending order.
NOTE: The above code does not handle edge cases where a property night be missing
Something like as follows (with lodash.js)
_.each(users, (u) => { u.dislikes = _.sortBy(u.dislikes, 'createdDate.time'); });
users = _.sortBy(users, 'dislikes[0].createdDate.time');
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?