jquery print object content - javascript

I'm new to jquery and want to print all times from monday only (or day == today later on)
I manage to print all times of the object and not 1 day I pick, maybe my iteration is wrong, would like any hints.
var arr = [{
"dateString": "2016-12-05",
"weekday": "mon",
"opening_hours": [{
"from": "09:00",
"to": "15:00",
"fromNumber": 9,
"toNumber": 15
}, {
"from": "17:00",
"to": "20:00",
"fromNumber": 17,
"toNumber": 20
}]
}, {
"dateString": "2016-12-06",
"weekday": "tue",
"opening_hours": [{
"from": "09:00",
"to": "17:00",
"fromNumber": 9,
"toNumber": 17
}]
}, {
"dateString": "2016-12-07",
"weekday": "wed",
"opening_hours": [{
"from": "09:00",
"to": "20:00",
"fromNumber": 9,
"toNumber": 20
}]
}, {
"dateString": "2016-12-08",
"weekday": "thu",
"opening_hours": [{
"from": "1:00",
"to": "11:00",
"fromNumber": 1,
"toNumber": 11
}]
}];
$("button").click(function() {
var today = new Date();
var str = today.toString('dddd, MMMM ,yyyy')
var sta = str.substring(0, 4);
console.log(sta);
$.each(arr, function(i, currProgram) {
$.each(currProgram.opening_hours, function(key, val) {
// $.each(num, function (axa, dasa) {
if (currProgram.weekday == "mon") {
console.log("monday");
timefrom = (val.from);
timeto = (val.to);
} else {
console.log("no monday");
}
// console.log(num[axa]);
$(".result").append("\ntime: " + timefrom + " to " + timeto + "\n");
console.log("time: " + timefrom + " to " + timeto + "\n");
// });
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="calnote">
<day></day>
<br>
<month></month>
<blackcorner>
<em>
<time></time>
</em>
</blackcorner>
</p>
<div id="div1">
<h2>click button for ajax</h2></div>
<div class="result">
<br>
</div>result</div>
<br>
<div class="result1">
</div>result1</div>
<p class="calnote">
<day></day>
<br>
<month></month>
<blackcorner>
<em>
<time></time>
</em>
</blackcorner>
</p>
click event
<button class="abc">Click me</button> here
jsfiddle
The result should print only:
time: 09:00 to 15:00
time: 17:00 to 20:00

You might want to move the logic console.log("time: " + timefrom + " to " + timeto + "\n"); into the if block
var arr = [{
"dateString": "2016-12-05",
"weekday": "mon",
"opening_hours": [{
"from": "09:00",
"to": "15:00",
"fromNumber": 9,
"toNumber": 15
}, {
"from": "17:00",
"to": "20:00",
"fromNumber": 17,
"toNumber": 20
}]
}, {
"dateString": "2016-12-06",
"weekday": "tue",
"opening_hours": [{
"from": "09:00",
"to": "17:00",
"fromNumber": 9,
"toNumber": 17
}]
}, {
"dateString": "2016-12-07",
"weekday": "wed",
"opening_hours": [{
"from": "09:00",
"to": "20:00",
"fromNumber": 9,
"toNumber": 20
}]
}, {
"dateString": "2016-12-08",
"weekday": "thu",
"opening_hours": [{
"from": "1:00",
"to": "11:00",
"fromNumber": 1,
"toNumber": 11
}]
}];
function buttonClick() {
var today = new Date();
var str = today.toString('dddd, MMMM ,yyyy')
var sta = str.substring(0, 4);
$.each(arr, function(i, currProgram) {
$.each(currProgram.opening_hours, function(key, val) {
if (currProgram.weekday == "mon") {
//console.log("monday");
timefrom = (val.from);
timeto = (val.to);
console.log("time: " + timefrom + " to " + timeto + "\n");
} else {
//console.log("no monday");
}
});
});
}
buttonClick()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How to merge two objects with same property in Node JS

I have a JSON Data like this:
"Data": [
{
"time": "18:40:43",
"count": 7,
"endTime": "15:46:25",
"date": "2019-01-16",
"dow": "Thursday"
},
{
"count": 11,
"time": "16:39:52",
"endTime": "19:41:03",
"dow": "Thursday",
"date": "2019-01-16"
},
]
I want to merge two objects in this array, but it have same properties like date, dow
at the end I want to represent data like this:
"Data": [
{
"time": "16:39:52",
"count": 18,
"date": "2019-01-16",
"dow": "Thursday"
"endTime": "19:41:03",
},
]
time: should be least from both objects and endTime should be largest of both of them
count should be sum of both. date and dow is common in both objects
How can I merge these object in this way in node JS?
const data=[
{
"time": "18:40:43",
"count": 7,
"endTime": "15:46:25",
"date": "2019-01-16",
"dow": "Thursday"
},
{
"count": 11,
"time": "16:39:52",
"endTime": "19:41:03",
"dow": "Thursday",
"date": "2019-01-16"
},
];
let date=(time)=>new Date().setHours(...time.split(":"));
let newData=[];
data.forEach((item)=>{
let findItem=newData.findIndex((e)=>e.date===item.date && e.dow===item.dow);
if(findItem!=-1){
let find=data.filter((e)=>e.dow===item.dow && e.date===item.date);
let time=find.filter((i)=>find.find(i2=>date(i2.time)>date(i.time)));
let endTime=find.filter((i)=>find.find(i2=>date(i2.endTime)<date(i.endTime)));
item.endTime=endTime?.[0]?.endTime || item?.endTime;
item.time=time?.[0]?.time || item?.time;
item.count=find.map((e)=>e.count).reduce((partialSum, a) => partialSum + a, 0);
let findItem=newData.findIndex((e)=>e.date===item.date && e.dow===item.dow);
if(findItem!=-1) newData.splice(findItem,1);
newData.push(item);
}
else newData.push(item);
});
console.log(newData);
Here's a simple and readable answer:
const data = [
{
time: "18:40:43",
count: 7,
endTime: "15:46:25",
date: "2019-01-16",
dow: "Thursday",
},
{
count: 11,
time: "16:39:52",
endTime: "19:41:03",
dow: "Thursday",
date: "2019-01-16",
},
];
const mergeObjects = (data) => {
mergedObj = { ...data[0] };
for (i = 1; i < data.length; i++) {
const obj = data[i];
for (const key in obj) {
switch (key) {
case "count":
mergedObj.count = (mergedObj.count || 0) + obj.count;
case "time":
mergedObj.time =
mergedObj.time < obj.time ? mergeObjects.time : obj.time;
case "endTime":
mergedObj.endTime = mergedObj.endTime > obj.endTime ? mergeObjects.endTime : obj.endTime;
}
}
}
return mergedObj;
};
console.log(mergeObjects(data));
output
{
"time": "16:39:52",
"count": 18,
"date": "2019-01-16",
"dow": "Thursday"
"endTime": "19:41:03",
},
Assuming
"Data" would have only two objects inside it
time would be in "HH::MM::SS" format
Pass the values onto constructJSON utility function which would return the formatted value
var Data = [
{
"time": "18:40:43",
"count": 7,
"endTime": "15:46:25",
"date": "2019-01-16",
"dow": "Thursday"
},
{
"count": 11,
"time": "16:39:52",
"endTime": "19:41:03",
"dow": "Thursday",
"date": "2019-01-16"
},
]
function constructJSON(data)
{
const returnData = {}
returnData['count'] = data[0].count + data[1].count
returnData['date'] = data[0].date // since its common for both
returnData['dow'] = data[0].dow // since its common for both
returnData['time'] = parseInt(data[0].time.split(':').join(''),10) < parseInt(data[1].time.split(':').join(''),10) ? data[0].time:data[1].time;
returnData['endTime'] = parseInt(data[0].endTime.split(':').join(''),10) > parseInt(data[1].endTime.split(':').join(''),10) ? data[0].endTime:data[1].endTime;
return returnData
}
console.log(constructJSON(Data))
If you use Array.reduce, you should be able to do this pretty easily, it should also expand to let you expand with more than just 2 objects in the array.
const data = [{
"time": "18:40:43",
"count": 7,
"endTime": "15:46:25",
"date": "2019-01-16",
"dow": "Thursday"
},
{
"count": 11,
"time": "16:39:52",
"endTime": "19:41:03",
"dow": "Thursday",
"date": "2019-01-16"
},
];
//res will contain the output
const res = data.reduce(function(acc, curr) {
//Initially the accumulator will be null
if (!acc) return curr;
//Add the counts up
acc.count += curr.count;
//Convert both times into dates and find the minimum
const accTime = new Date(acc.date + 'T' + acc.time); //We add the T here since that's just how the Date constructor accepts times
const currTime = new Date(acc.date + 'T' + curr.time);
acc.time = new Date(Math.min(accTime, currTime)).toTimeString().split(' ')[0]; //See https://stackoverflow.com/questions/19346405/how-to-get-hhmmss-from-date-object
//Do the same for the end times but find the maximum
const accEndTime = new Date(acc.date + 'T' + acc.endTime);
const currEndTime = new Date(acc.date + 'T' + curr.endTime);
acc.endTime = new Date(Math.max(accEndTime, currEndTime)).toTimeString().split(' ')[0];
return acc;
});
console.log(res);
Another way of merging - all keys are combined, the common keys are overwritten by the second object, but count, time and endTime are calculated by special conditions
const
data = [{"time": "18:40:43","count": 7,"endTime": "15:46:25","date": "2019-01-16","dow": "Thursday"},{"count": 11,"time": "16:39:52","endTime": "19:41:03","dow": "Thursday","date": "2019-01-16"}],
[first, last] = data,
dumbDate = '2000-01-01 ',
result = {
...first,
...last,
count: first.count + last.count,
time: (new Date(`${dumbDate}${first.time}`) < new Date(`${dumbDate}${last.time}`)) ? first.time : last.time,
endTime: (new Date(`${dumbDate}${first.endTime}`) > new Date(`${dumbDate}${last.endTime}`)) ? first.endTime : last.endTime,
};
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
Use Array#reduce() and Array#map() methods as follows:
const data = {"Data": [{"time": "18:40:43", "count": 7, "endTime": "15:46:25", "date": "2019-01-16", "dow": "Thursday"}, {"count": 11, "time": "16:39:52", "endTime": "19:41:03", "dow": "Thursday", "date": "2019-01-16" }]};
const newD = {Data:data.Data.reduce(
(prev,{date,dow,count,...r}) =>
//check if an element in array prev has dow & date props equal to the current element
prev.findIndex(p => p.date === date && p.dow === dow) > -1 ?
//If found process the matching element
prev.map(({date:d,dow:w,count:c,...rs}) =>
d === date && w === dow ?
({...rs,date:d,dow:w,count:c+count,time:rs.time < r.time ? rs.time : r.time,endTime:rs.endTime > r.endTime ? rs.endTime : r.endTime}) :
({...rs,date:d,dow:w,count:c})
) :
//If not add the current element to array prev
prev.concat({...r,date,dow,count}),
//start off with an empty array
[]
)};
console.log( newD );

JS\Node Reduce group by multiple properties and summarize JSON data

I have following data that i'm trying to group summarize and add back to related object.
{
"Schedule": [
{
"AppointmentId": 123456,
"Start": "2021-11-02T09:00:00.000Z",
"Location": 87925,
"InsuranceName": "Geico",
"InsuranceFinancialClass": "Commercial",
"AppointmentName": "Online",
"LocalDate": "11/02/2021",
"LocalTime": "9:00 AM",
"TimeOfDay": "AM"
},
{
"AppointmentId": 123457,
"Start": "2021-11-03T10:00:00.000Z",
"Location": 87925,
"InsuranceName": "Farmers",
"InsuranceFinancialClass": "Commercial",
"AppointmentName": "InPerson",
"LocalDate": "11/03/2021",
"LocalTime": "10:00 AM",
"TimeOfDay": "AM"
},
{
"AppointmentId": 123458,
"Start": "2021-11-03T11:00:00.000Z",
"Location": 87925,
"InsuranceName": "Farmers",
"InsuranceFinancialClass": "Commercial",
"AppointmentName": "InPerson",
"LocalDate": "11/03/2021",
"LocalTime": "11:00 AM",
"TimeOfDay": "AM"
}
]
}
I would like the final result to look like the following:
{
"Schedule": [
{
"AppointmentId": 123456,
"Start": "2021-11-02T09:00:00.000Z",
"Location": 87925,
"InsuranceName": "Geico",
"InsuranceFinancialClass": "Commercial",
"AppointmentName": "Online",
"LocalDate": "11/02/2021",
"LocalTime": "9:00 AM",
"TimeOfDay": "AM",
"Summary": {
"InsuranceName": {
"Total": 1,
"Geico": 1
},
"InsuranceFinancialClass": {
"Total": 1,
"Commercial": 1
},
"AppointmentName": {
"Total": 1,
"Online": 1,
"InPerson": 1
},
"LocalDate": {
"Total": 1,
"11/02/2021": 1,
}
}
},
{
"AppointmentId": 123457,
"Start": "2021-11-03T10:00:00.000Z",
"Location": 87925,
"InsuranceName": "Farmers",
"InsuranceFinancialClass": "Commercial",
"AppointmentName": "InPerson",
"LocalDate": "11/03/2021",
"LocalTime": "10:00 AM",
"TimeOfDay": "AM",
"Summary": {
"InsuranceName": {
"Total": 2,
"Farmers": 2
},
"InsuranceFinancialClass": {
"Total": 2,
"Commercial": 2
},
"AppointmentName": {
"Total": 2,
"InPerson": 2
},
"LocalDate": {
"Total": 2,
"11/03/2021": 2
}
}
}
{
"AppointmentId": 123458,
"Start": "2021-11-03T11:00:00.000Z",
"Location": 87925,
"InsuranceName": "Farmers",
"InsuranceFinancialClass": "Commercial",
"AppointmentName": "InPerson",
"LocalDate": "11/03/2021",
"LocalTime": "11:00 AM",
"TimeOfDay": "AM",
"Summary": {
"InsuranceName": {
"Total": 2,
"Farmers": 2
},
"InsuranceFinancialClass": {
"Total": 2,
"Commercial": 2
},
"AppointmentName": {
"Total": 2,
"InPerson": 2
},
"LocalDate": {
"Total": 2,
"11/03/2021": 2
}
}
}
]
}
I have following JS code that:
const props = ['LocalDate', 'AppointmentName', 'InsuranceFinancialClass', 'InsuranceName'];
const result = JSONData.reduce((r, e) => {
Object.entries(e).forEach(([k, v]) => {
if (props.includes(k)) {
if (!r[k]) r[k] = {};
r[k].Total = (r[k].Total || 0) + 1;
r[k][v] = (r[k][v] || 0) + 1;
}
});
return r;
}, {});
{
"Schedule": {
"InsuranceName": {
"Total": 3,
"Geico": 1,
"Farmers": 2
},
"InsuranceFinancialClass": {
"Total": 3,
"Commercial": 3
},
"AppointmentName": {
"Total": 3,
"Online": 1,
"InPerson": 2
},
"LocalDate": {
"Total": 3,
"11/02/2021": 1,
"11/03/2021": 2
}
}
}
How should the code be written produce desired result?
The summary object should be aggregate by date and appended to original object that matches the date.
Thanks in advance for your help and suggestions.
I was able to work out a solution but not sure if it's efficient.
const props = ['LocalDate', 'AppointmentName', 'InsuranceFinancialClass', 'InsuranceName'];
const groupedByDateSummary = filteredByPatientAppointment.reduce((r, e) => {
if (!r[e.LocalDate]) r[e.LocalDate] = {};
Object.entries(e).forEach(([k, v]) => {
if (props.includes(k)) {
if (!r[e.LocalDate][k]) r[e.LocalDate][k] = {};
r[e.LocalDate][k].Total = (r[e.LocalDate][k].Total || 0) + 1;
r[e.LocalDate][k][v] = (r[e.LocalDate][k][v] || 0) + 1;
}
});
return r;
}, {});
const slotObjWithSummary = _.each(filteredByPatientAppointment, (summary) => {
for (const [key, value] of Object.entries(groupedByDateSummary)) {
if (key === summary.LocalDate) {
summary.Summary = value;
}
}
return summary;
});

Getting dates from JSON for D3

My JSON file has the dates separated like this:
"time": {
"date": {
"year": 2018,
"month": 2,
"day": 25
},
"time": {
"hour": 10,
"minute": 19,
"second": 6,
"nano": 19000000
}
},
The tutorial I used to get a line graph in d3 going was in this link:
https://datawanderings.com/2019/10/28/tutorial-making-a-line-chart-in-d3-js-v-5/
Using the code below:-
const timeConv = d3.timeParse("%d-%b-%Y");
const dataset = d3.csv(datacsv);
dataset.then(function(data) {
var slices = data.columns.slice(1).map(function(id) {
return {
id: id,
values: data.map(function(d){
return {
date: timeConv(d.date),
measurement: +d[id]
};
})
};
});
});
How could I use the same code but use the JSON file with the separated date values?
Just make up the actual date string from the separate dates:
return {
date: timeConv(d.time.date.day + '-' + d.time.date.month + '-' + d.time.date.year),
measurement: +d[id]
};
Since the month is not described as the abbreviated month name, you need to change timeConv as
const timeConv = d3.timeParse("%d-%m-%Y");
An json data example:
let dataset = [{
"id": 1,
"time": {
"date": {
"year": 2018,
"month": 2,
"day": 25
},
"time": {
"hour": 10,
"minute": 19,
"second": 6,
"nano": 19000000
}
}
}, {
"id": 2,
"time": {
"date": {
"year": 2019,
"month": 2,
"day": 25
},
"time": {
"hour": 10,
"minute": 19,
"second": 6,
"nano": 19000000
}
}
}]
const timeConv = d3.timeParse("%d-%m-%Y");
newData = dataset.map(function(d) {
return {
date: timeConv(d.time.date.day + '-' + d.time.date.month + '-' + d.time.date.year),
measurement: +d.id
}
})
console.log(newData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

How can I compare Javascript dates to filter objects in an array?

I've been stuck on this for days and dates in JavaScript are quite confusing.
I need to iterate some JSON and filter objects that are less than 2h ahead and more than 2 months ahead.
here is an example of the JSON:
[
{
"Email":"example#email.com",
"TimeSlotsDate":"2017-01-28",
"TimeSlotsAvailable":[
{
"start":"11:00",
"end":"12:00"
},
{
"start":"12:00",
"end":"13:00"
},
{
"start":"13:00",
"end":"14:00"
},
{
"start":"15:00",
"end":"16:00"
},
{
"start":"16:00",
"end":"17:00"
},
{
"start":"17:00",
"end":"18:00"
}
],
},
{
"Email":"example#email.com",
"TimeSlotsDate":"2017-02-01",
"TimeSlotsAvailable":[
{
"start":"12:00",
"end":"13:00"
},
{
"start":"13:00",
"end":"14:00"
},
{
"start":"14:00",
"end":"15:00"
},
{
"start":"15:00",
"end":"16:00"
},
{
"start":"16:00",
"end":"17:00"
},
{
"start":"17:00",
"end":"18:00"
}
],
}]
I have written a function that creates usable dates from the JSON but I am stuck at the part where I remove the objects from the TimeSlotsAvailable array that are less than 2h ahead and more than 2 months ahead as mentioned.
Here is the function:
var filterTimeslots = function (_timeSlots) {
var result = [];
var currentDate = new Date();
var timeZoneOffset = currentDate.getTimezoneOffset() / 60;
for (var i in _timeSlots) {
var day = _timeSlots[i].TimeSlotsDate.substring(8, 10);
var month = _timeSlots[i].TimeSlotsDate.substring(5, 7);
var year = _timeSlots[i].TimeSlotsDate.substring(0, 4);
for (var x in _timeSlots[i].TimeSlotsAvailable) {
var timeSlotStrt = _timeSlots[i].TimeSlotsAvailable[x].start.substring(0, 2);
var timeZoneTime = parseInt(timeSlotStrt) - timeZoneOffset;
var timeSlotDate = new Date(year, month, day, timeZoneTime);
if (timeSlotDate < currentDate) {
//the timeslot is less than 2 hours away
}
if (timeSlotDate > currentDate) {
//the timeslot is more than 2 months ahead
}
return result;
}
}
};
The function should return a filtered array that excludes the invalid time slots.
Any help would be greatly appreciated.
using moment should be easy
var arr = [{
"Email": "example#email.com",
"TimeSlotsDate": "2016-08-16",
"TimeSlotsAvailable": [{
"start": "17:00",
"end": "18:00"
}],
}, {
"Email": "example#email.com",
"TimeSlotsDate": "2017-02-08",
"TimeSlotsAvailable": [{
"start": "11:00",
"end": "12:00"
}, {
"start": "12:00",
"end": "13:00"
}, {
"start": "13:00",
"end": "14:00"
}, {
"start": "15:00",
"end": "16:00"
}, {
"start": "16:00",
"end": "17:00"
}, {
"start": "17:00",
"end": "18:00"
}],
}, {
"Email": "example#email.com",
"TimeSlotsDate": "2017-02-01",
"TimeSlotsAvailable": [{
"start": "12:00",
"end": "13:00"
}, {
"start": "13:00",
"end": "14:00"
}, {
"start": "14:00",
"end": "15:00"
}, {
"start": "15:00",
"end": "16:00"
}, {
"start": "16:00",
"end": "17:00"
}, {
"start": "17:00",
"end": "18:00"
}],
}];
var now = moment();
var start = now.clone().add(2, 'hours');
var end = now.clone().add(2, "months");
console.log("NOW: ",now);
console.log("START: ",start);
console.log("END: ",end);
var res = arr.filter(function(el) {
return el.TimeSlotsAvailable.filter(function(subEl) {
var c = moment(el.TimeSlotsDate + " " + subEl.start);
return c >= start && c <= end;
}).length == el.TimeSlotsAvailable.length;
});
console.log(res.length, res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

json array needs to be formatted based text containing time in angularjs application

In my angular js application, I have the following json array
$scope.timeList = [
{
"text": " 4:00 am",
"value": "17"
},
{
"text": " 4:15 am",
"value": "18"
},
{
"text": " 4:30 am",
"value": "19"
},
{
"text": " 3:45 pm",
"value": "64"
},
{
"text": " 4:00 pm",
"value": "65"
},
{
"text": " 4:15 pm",
"value": "66"
}
]
And I need to convert it into the following format :
$scope.timeFormattedList = [
{
"text": " 4:00 am",
"unique" : "4.00",
"value": "17"
},
{
"text": " 4:15 am",
"unique" : "4.15",
"value": "18"
},
{
"text": " 4:30 am",
"unique" : "4.30",
"value": "19"
},
{
"text": " 3:45 pm",
"unique" : "15.45",
"value": "64"
},
{
"text": " 4:00 pm",
"unique" : "16.00",
"value": "65"
},
{
"text": " 4:15 pm",
"unique" : "16.15",
"value": "66"
}
]
Here the new key "unique" is added to each json object based "text" key. If the "text" contains "pm" it should add 12 to it, otherwise same value remains.
You can use .map, and to get unique value you can use .replace method with callback
var $scope = {};
$scope.timeList = [{
"text": " 4:00 am",
"value": "17"
}, {
"text": " 4:15 am",
"value": "18"
}, {
"text": " 4:30 am",
"value": "19"
}, {
"text": " 3:45 pm",
"value": "64"
}, {
"text": " 4:00 pm",
"value": "65"
}, {
"text": " 4:15 pm",
"value": "66"
}];
$scope.timeFormattedList = $scope.timeList.map(function (el) {
var unique = el.text.trim().replace(/(\d+):(\d+)\s(\w{2})/,
function (match, hour, minutes, meridiem) {
return (meridiem === 'pm' ? (+hour + 12) : hour) + '.' + minutes;
});
return {
text: el.text,
unique: unique,
value: el.value
}
});
snippet.log(JSON.stringify($scope.timeFormattedList));
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Try this:
var timeList = [
{
"text": " 4:00 am",
"value": "17"
},
{
"text": " 4:15 am",
"value": "18"
},
{
"text": " 4:30 am",
"value": "19"
},
{
"text": " 3:45 pm",
"value": "64"
},
{
"text": " 4:00 pm",
"value": "65"
},
{
"text": " 4:15 pm",
"value": "66"
}
];
timeList.forEach(function(obj) {
var m = obj.text.match(/ ([0-9]+):([0-9]+) (.+)/);
console.log(m[3]);
if (m[3] == 'pm') {
m[1] = +m[1]+12;
}
obj.unique = m[1] + "." + m[2];
});
document.getElementById('output').innerHTML = JSON.stringify(timeList);
<div id="output"></div>
The easiest way is to use map() method.
$scope.timeFormattedList = $scope.timeList.map(function(value){
var match = value.text.match(/(\d+):(\d+)\s*(\w+)/);
var nvalue = {
'text': value.text,
'unique': (match[3] == 'pm' ? parseInt(match[1]) + 12 : match[1]) + "." + match[2],
'value': value.value
};
return nvalue
});
plunker code here
Try this
$scope.timeFormattedList = $scope.timeList.map(function(item){
var textArray = item.text.trim().split(" ");
var timeArray = textArray[0].split(":");
if(textArray[1] === "pm") {
if(timeArray[0] != 12) {
item.unique = parseInt(timeArray[0])+12+":"+timeArray[1];
} else {
item.unique = textArray[0];
}
} else {
if(timeArray[0] != 12) {
item.unique = textArray[0];
} else {
item.unique = "00:"+timeArray[1];
}
}
return item;
});
Added specific handling for 12 am and 12 pm timings.

Categories

Resources