Filter out an array in AngularJS - javascript

I have a JSON object that is returned to me from my Web Service which I have added to an array in my AngularJS project.
I need to create a array that looks like this:
$scope.eventSources = [
//this is event source object #1
{
events: [ // put the array in the `events` property
{
title: //POPULATE FROM MY ARRAY,
start: //POPULATE FROM MY ARRAY,
END: //POPULATE FROM MY ARRAY
},
{
title: //POPULATE FROM MY ARRAY,
start: //POPULATE FROM MY ARRAY,
end: //POPULATE FROM MY ARRAY
}
],
}];
from an array that looks like this:
holidays: [
{
HOLIDAY_END: "/Date(1461538800000+0100)/"
HOLIDAY_EVENT_ID: 1
HOLIDAY_START: "/Date(1461106800000+0100)/"
HOLIDAY_TITLE: "Spain "
USER_ID: 1
}
]
So as you can see the HOLIDAY TITLE, HOLIDAY START AND HOLIDAY END need to get added to a new array.

This should be doable with a forEach loop that goes through your holidays and creates an object with the required field from each element in your holidays. This code should do the trick:
$scope.eventSources = [{events:[]}]; //set up object with array for containing data
var func = function() { //Lets do it in a function so it's reusable
holidays.forEach(function(hol) { //forEach loop through the holidays array data
$scope.eventSources[0].events.push({ //Push a new object to our eventSOurces array
title: hol.HOLIDAY_TITLE, //Set up fields on new object
start: hol.HOLIDAY_START,
end: hol.HOLIDAY_END
});
});
}
func(); //Call function to populate array
You switched between END and end in your request, so I've went with end as it's consistent with the other fields.

This is a proposal with Array#map()
var data = {
holidays: [{
HOLIDAY_END: "/Date(1461538800000+0100)/",
HOLIDAY_EVENT_ID: 1,
HOLIDAY_START: "/Date(1461106800000+0100)/",
HOLIDAY_TITLE: "Spain",
USER_ID: 1
}, {
HOLIDAY_END: "/Date(1462538800000+0100)/",
HOLIDAY_EVENT_ID: 2,
HOLIDAY_START: "/Date(1461106800000+0100)/",
HOLIDAY_TITLE: "France",
USER_ID: 2
}]
},
$scope = { eventSources: [{}] };
$scope.eventSources[0].events = data.holidays.map(function (a) {
return {
title: a.HOLIDAY_TITLE,
start: a.HOLIDAY_START,
end: a.HOLIDAY_END
};
});
document.write('<pre>' + JSON.stringify($scope, 0, 4) + '</pre>');

Related

How to create a json grouped by date in js?

I have an array of objects sorted by date:
const alerts = [{
id: 1, date: '2018-10-31T23:18:31.000Z', name: 'Joke', title: 'this is the first 1'
}, {
id: 2, date: '2018-10-30T23:18:31.000Z', name: 'Mark', title: 'this is the second one'
}]
I am trying to 'group' the alerts by date so trying to create 'datesections' which have a dateheader, the result should be something like:
const sections = [{
date: '2018-10-31T23:18:31.000Z',
heading: 'today',
alerts: [{ id: 1, date: '2018-10-31T23:18:31.000Z', name: 'Joke',
title: 'this is the first one' }]
}, {
date: '2018-10-30T23:18:31.000Z',
heading: 'Yesterday',
alerts: [{ id: 2, date: '2018-05-30T23:18:31.000Z', name: 'Mark',
title: 'this is the second one' }]
}]
I tried something this but can't figure out how to get the alerts with the same date in the alerts prop:
const sections2=alerts.map(a =>
({
date: a.date,
heading:'today new',
alerts:alerts
})
)
const alerts = [
{ id: 1, date: '2018-10-31T23:18:31.000Z', name: 'Joke', title: 'this is the first 1' },
{ id: 2, date: '2018-05-30T23:18:31.000Z', name: 'Mark', title: 'this is the second one' }
]
const grouping = _.groupBy(alerts, element => element.date.substring(0, 10))
const sections = _.map(grouping, (items, date) => ({
date: date,
alerts: items
}));
console.log(sections);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Can't help you with headings - what if it's neither "today" or "yesterday"?
I feel like you are asking a couple of things here. The key one is how to group by day with a date.
To do that you will first need to know how to group. This answer may help with that.
As far as how to group by day there are a number of ways to do that. Simplest I can think of is to cut off everything after the "T" in the date string and sort that.
From my point of view it's not really a map what you need here, map will return a new array but not what you want. You can do this with 2 for statements
let total = [];
for (let j = 0; j < alerts.length; j++) {
let item = alerts[j];
let foundDate = false;
for (let i = 0; i < total.length; i++) {
if (total[i].date === item.date) {
foundDate = true;
total.alerts.push(item);
}
}
if (!foundDate) {
console.log("!found");
total.push({
date: item.date,
heading: "Yesterday",
alerts: [item]
});
}
}
If you console.log yout total array, will contain what you want.
If you need any other explanation pls let me know.
You can use a regular expression to match the part of the date you want and then group your data. You can add there the header you want. Hope this helps.
const alerts = [
{ id: 1, date: '2018-10-31T23:18:31.000Z', name: 'Joke', title: 'this is the first 1' },
{ id: 2, date: '2018-10-30T23:18:31.000Z', name: 'Mark', title: 'this is the second one' },
{ id: 3, date: '2018-10-30T23:14:32.000Z', name: 'Mark', title: 'this is the third one' }
];
const groupByDate = (data) => {
return data.reduce((acc, val) => {
const date = val.date.match(/\d{4}-\d{2}-\d{2}/g).toString();
const item = acc.find((item) => item.date.match(new RegExp(date, 'g')));
if (!item) acc.push({ date: val.date, alerts: [val], heading: 'some heading' });
else item.alerts.push(val);
return acc;
}, []);
};
console.log(groupByDate(alerts));
Maybe you need something like this? Didn't have much time for this and last array parsing might be done in more elegant way ;)
var alerts = [
{ id: 1, date: '2018-10-31T23:18:31.000Z', name: 'Joke', title: 'this is the first 1' },
{ id: 3, date: '2018-10-31T23:44:31.000Z', name: 'Joke1', title: 'this is the 2nd' },
{ id: 2, date: '2018-10-30T23:18:31.000Z', name: 'Mark', title: 'this is the second one' },
{ id: 4, date: '2018-10-30T23:45:31.000Z', name: 'Mark1', title: 'this is the 3rd' },
{ id: 5, date: '2018-10-27T23:18:31.000Z', name: 'Mark2', title: 'this is the 4th' },
];
var processedAlerts = [], finalAlerts;
(function(initAlerts){
//iterate through array to make keys to group by day
for(var i = 0; i < initAlerts.length; i++){
processedAlerts[i] = initAlerts[i];
//substring here can be more sophisticated - this was faster
initAlerts[i].keyDate = initAlerts[i].date.substr(0, 10);
}
//supporting function to convert string to date
//to acheve more detailed sorting that includes time
//just use date object and use hours, minutes and/or seconds to create Date object
function dateFromString(strDate){
var date, tmpDate;
//convert string to array - I assume that date format is always the same
//yyyy-mm-dd and will become Array 0: year, 1: month, 2: day of the month
tmpDate = strDate.split("-");
//moths in js are zero pased so Jan is 0, Feb is 1 and so on
//so we want to substract 1 from human readable month value to get correct date
date = new Date(tmpDate[0], tmpDate[1]-1, tmpDate[2]);
return date;
}
//function used to compare dates and passed to sort function
function comparedates(obj1, obj2){
var date1, date2;
date1 = dateFromString(obj1.keyDate);
date2 = dateFromString(obj2.keyDate);
let comparison = 0;
if(date1>date2){
comparison = 1;
} else if(date1<date2){
comparison = -1;
}
//to achieve reverse just multiply comparison result by -1
return comparison*(-1);
}
function getHeader(date){
//here place logic to generate header
//this involves comparing dates probably from keyDate
return "temp header: " + date.toString()
}
//sort the array by keyDate from newest to oldest
processedAlerts.sort(comparedates);
//final array rebuild
//pass here sorted array
finalAlerts = (function(arrayAlerts){
var aAlerts = [], k = 0;
for(var j = 0; j < arrayAlerts.length; j++){
//check if entry for date exists
//if no than create it
if(!aAlerts[k]){
aAlerts[k] = {
//removed title because I asummed that each alert has unique title and put them in alerts instead
date: arrayAlerts[j].keyDate, //agroupped date
heading: getHeader(arrayAlerts[j].keyDate), //update this function to return personalized heading
//here you can shape the alert object how you need
//I just passed it as it was
alerts: [arrayAlerts[j]] //array with first object inside
};
} else {
//add another alert to day
aAlerts[k].alerts.push(arrayAlerts[j]) //array with first object inside
}
//increasing final array key
//if there is previous entry and keys are the same for current and previous
if(arrayAlerts[j-1] && (arrayAlerts[j].keyDate == arrayAlerts[j-1].keyDate)){
k++;
}
}
return aAlerts;
})(processedAlerts);
})(alerts);
console.log(finalAlerts);

How to get JSON keys and add extra fields?

I'm trying to get the key of these json objects in order to create a new object with extra filed to create table headers in a React app. JSON data:
let example = [
{
id: 1,
city: 'New York',
},
{
id: 2,
city: 'Paris',
},
]
The function:
getKeys() {
return example.map((key) => {
return {
cityName: key, // gets the whole array
capital: false,
};
});
}
I tries Object.keys( example);, it returns integers; 0, 1.
How can I get the keys in this case? Thanks.
You are trying to map the keys for an array since example is an array. If the data are consistent throughout the array get the first element example[0] and do Object.keys().
So Object.keys(example[0])
There's no need to get the keys if you just want to add a property to the items in the array. I think there's a misunderstanding about .map, which gives you a single item/object in the array, not the keys.
Something like this perhaps?
let example = [{
id: 1,
city: 'New York',
}, {
id: 2,
city: 'Paris',
}];
const modifiedArray = function(arr) {
return arr.map(item => {
return {
id: item.id,
cityName: item.city,
capital: false,
};
})
}
const newArray = modifiedArray (example);
console.log(newArray )

How do you create Object of Arrays in Javascript

I spent more time on this than I would like to admit. I have trouble constructing an object filled with an array.
I would like my data to look like this:
items={
{
'2012-05-22': [{text: 'item 1 - any js object'}],
'2012-05-23': [{text: 'item 2 - any js object'}],
'2012-05-24': [],
'2012-05-25': [{text: 'item 3 - any js object'},{text: 'any js object'}],
}
}
I am making a database call and the data I receive looks like this:
Object {start: "08:00:00", end: "09:00:00", full_name: "Tomomi", date: "2017-06-08", Barber_id: "1"…}
The data I am interested in is the full_name value and the date value.
This is what I have attempted:
let newItems = {};
axios.post(endpoint, {lookup: day.dateString}).then((customerData) => {
customerData.data.forEach((val,key)=>{
newItems = {[val.date]:[]};
newItems[val.date].push({name:val.full_name});
console.log(newItems);
})
}
It looks like this:
Object {2017-06-08: Array(1)}
2017-06-08
:
Array(1)
This is very close, but the problem is that my code is overwriting my data.
I am trying to create this dynamically:
'2012-05-25': [{text: 'item 3 - any js object'},{text: 'any js object'}],
So that each date can have many users. Hopefully, this makes sense.
Thanks for any help.
The function expression you pass to forEach has this as the first line:
newItems = {[val.date]:[]};
This resets the newItems object to an object with one date:name pair. You really want something more like:
newItems[val.date]?newItems[val.date].push({name:val.full_name}):newItems[val.date]=[];
var byDate = {}; // Object to store received data by-date
function addIntoByDate( obj ) {
byDate[obj.date] = byDate[obj.date] || [];
byDate[obj.date].push( obj );
}
// Simulate adding server data one by one
addIntoByDate( {date: "2017-06-08", full_name: "Cat", text:"Foo!!"} ); // < SAME DATE
addIntoByDate( {date: "2016-05-23", full_name: "Dog", text:"Bar"} );
addIntoByDate( {date: "2017-06-08", full_name: "Bug", text:"Baz..."} ); // < SAME DATE
// test
console.dir(byDate);
You can use object destructuring, computed property and Object.assign()
const newItems = {};
const data = [
{
start: "08:00:00"
, end: "09:00:00"
, full_name: "Tomomi"
, date: "2017-06-08"
, Barber_id: "1"
}
];
data.forEach(({date, full_name}) =>
Object.assign(newItems, {[date]: [{/* text: */ full_name}]}));
console.log(newItems);

Create list of object members from object list

Assume I have a list of objects like so:
var list = [
{ date: '22/9/2016', status: 1, id: '11111' },
{ date: '23/9/2016', status: 1, id: '22222' },
{ date: '24/9/2016', status: 1, id: '33333' }
];
I would like to create a list of the ids of all the objects in the above list, so that I end up with:
var idList = ['11111', '22222', '33333'];
Obviously, I could iterate through the list and build the idList manually.
Is there an alternative way of doing this through either native JS, angularJS, or perhaps another library.
Manually iterating through the list isn't a big overhead, I just want to ensure I'm not ignoring functionality of JS / angularJS that would do this for me instead.
You can use Array map
var list = [
{ date: '22/9/2016', status: 1, id: '11111' },
{ date: '23/9/2016', status: 1, id: '22222' },
{ date: '24/9/2016', status: 1, id: '33333' }
];
var idList = list.map(item => item.id );
console.log(idList);
Use
var ids = list.map(function(item) { return item.id});
Should work.

How to create a customized javaScript array?

I have a little web app. And I use a calender(code from here FullCalendar) there inside a .jsp file.
I use Spring mvc architecture. So when this page loaded a controller which is responsible for this page loading will add an attribute called calendarEventList to the model.
'calendarEventList' is an ArrayList<calObject>. calObject is a class which contain the details about the even.
I can access those details in the jsp by ${calEvent.eventID} where calEvent is an Object from that ArrayList.
In FullCalendar the event load can be called like below
$('#calendar').fullCalendar({
events: [
{
title : 'event1',
start : '2010-01-01'
},
{
title : 'event2',
start : '2010-01-05',
end : '2010-01-07'
},
{
title : 'event3',
start : '2010-01-09 12:30:00',
allDay : false // will make the time show
}
]
});
I want is like below
$('#calendar').fullCalendar({
events: //read the `calendarEventList` and create a suitable array
});
I have title ,start ,end .. details in a Oblect of the calendarEventList.
So I want to create the list which I need to give to the fullcalendar. How can I create such a kind of array in JS.
It's structure should match [{},{},{},...,{},{}] as given in the example. {} includes a detail about one Object in that calendarEventList ArrayList.
any detailed description will be highly appreciated.
If i truly understand your question ( you have array of objects, all objects contains different field, but each object contains title, start (and end)). So your task is filter this array.
Solution:
function factory(array){
return array.map(function(item){
var instance = {title: item.title, start: item.start};
if(item.end) instance.end = item.end;
return item;
});
}
var res = factory([{ item: 1, title: 2, start: 4, an: 123, pp: "asdf"}, { item: 2, title: 2, start: 4, end: 5}, { item: 3, title: 2, start: 4}]);
Output will be filtered array of objects with start, title, (end) fields;
Try demo
Let try with my example:
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var employees = [];
employees.push({ id: 111, title: "Testing Event 001", start: new Date(y, m, d-5,10,30) , end: new Date(y, m, d-5,12,30),className: ['yellow-event', 'black-text-event']});
employees.push({ id: 111, title: "Testing Event 002", start: new Date(y, m, d-3,10,30) , end: new Date(y, m, d-3,12,30),className: ['yellow-event', 'black-text-event']});
on events: employees put like this,,
Hope it help full. thanks you..

Categories

Resources