I pretend to do console.log of the holidays variable appear in the list and not as an array. How do I get this information as a simple object?
My json:
[{
"2016-10-10":[{"name":"Columbus Day","country":"US","date":"2016-10-10"}],
"2016-10-31":[{"name":"Halloween","country":"US","date":"2016-10-31"}]
}]
My app:
app.factory('calendario', function($http) {
return{
getJobs : function() {
return $http({
url: '/app/components/home/controller/test_calendar.json',
method: 'GET'
})
}
}
});
controller:
var holidays = [];
calendario.getJobs().success(function(data){
holidays.push(data[0]);
});
$scope.setDayContent = function(date) {
console.log(holidays);
};
Example:
I want this
I don't want this
Instead of a list use a map
holidays = {}
Then put the items in the map with key the date and value the array:
holidays[data[0].date] = data[0].days;
But it looks like you already have the map, so probably you can just save data directly instead of pushing it in a list:
var holidays = {};
calendario.getJobs().success(function(data){
holidays=data;
});
$scope.setDayContent = function(date) {
console.log(holidays);
};
This question is to easy ... no?
var holidays = [];
calendario.getJobs().success(function(data){
holidays=data[0];
});
$scope.setDayContent = function(date) {
console.log(holidays);
};
You want to flatten it, so, Nick is right, do not use the array, use dict/hash instead. In case your functionality will suffer you can use some workaround:
var holidays = [{
"2016-10-10":[{"name":"Columbus Day","country":"US","date":"2016-10-10"}],
"2016-10-31":[{"name":"Halloween","country":"US","date":"2016-10-31"}]
}];
var flatten_holidays = holidays.reduce(function(elem){return elem});
I do not feel like it is specifically AngularJS question, more like common JavaScript instead. For your example it would be:
var holidays = [];
calendario.getJobs().success(function(data){
holidays.push(data[0]);
});
$scope.setDayContent = function(date) {
console.log(holidays.reduce(function(elem){return elem}));
};
or, if the preference is to use dict/hash:
var holidays = {};
calendario.getJobs().success(function(data){
//if data is: {"2016-10-10":[{"name":"Columbus day","country":"US","date":"2016-10-10"}]}
var key = Object.keys(data)[0];
var value = data[key];
holidays[key] = value;
});
$scope.setDayContent = function(date) {
console.log(holidays);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.