José Cerejo José Cerejo - 21 days ago 4
AngularJS Question

How do access a json object 0 using a javascript

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

enter image description here

I don't want this

enter image description here

Answer

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