0

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.

asked Feb 17, 2016 at 18:06

2 Answers 2

2

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.

answered Feb 17, 2016 at 18:10
Sign up to request clarification or add additional context in comments.

Comments

0

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>');

answered Feb 17, 2016 at 18:17

1 Comment

Can this work if the array returned back to me contains more holidays in the array?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.