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.
2 Answers 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.
Comments
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>');