VolcovMeter VolcovMeter - 4 months ago 8
JSON Question

AngularJS: How to create new arrays from JSON response?

I have a function tied to the factory for my controller:

fac.GetDailyCountersList = function () {
return $http.get('/Data/GetDailyCountersList')
}


Inside the controller, here's where the function is called:

$scope.DailyCounters = null;
DailyCounterService.GetDailyCountersList().then(function (d) {
$scope.DailyCounters = d.data;
}, function (error) {
alert('Error!');
});


Based on this, if I were to output the variable on the html page, this would show:

[{"Id":1,"MIDay":"16","MITime":"900","MICounter":0},
{"Id":2,"MIDay":"16","MITime":"915","MICounter":1},
{"Id":3,"MIDay":"16","MITime":"930","MICounter":0},
{"Id":4,"MIDay":"17","MITime":"945","MICounter":0},
{"Id":5,"MIDay":"17","MITime":"1000","MICounter":0},
{"Id":6,"MIDay":"17","MITime":"1015","MICounter":52},
{"Id":7,"MIDay":"18","MITime":"1030","MICounter":2},
{"Id":8,"MIDay":"18","MITime":"1045","MICounter":3},
{"Id":9,"MIDay":"18","MITime":"1100","MICounter":0}]


My question is how to take this data and create other arrays based on one of the properties of the Json data.

For example, how would I put arrays

{"Id":1,"MIDay":"16","MITime":"900","MICounter":0},
{"Id":2,"MIDay":"16","MITime":"915","MICounter":1},
{"Id":3,"MIDay":"16","MITime":"930","MICounter":0}


Into a new array "ArrayDay16"? And the rest into their respective arrays as well.

I was thinking about doing it this way:

var myArray = [];
if (d.data['MIDay'] == '16')
myArray.push(d.data);


But this is incorrect/fails. Any ideas for an efficient solution?

Answer

Use the filter function to populate new arrays. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

//This will populate "someArray" with only the data that has MIDAY = 16
DailyCounterService.GetDailyCountersList().then(function (d) {
    $scope.someArray = d.data.filter(function(ele) {
        return ele.MIDAY === '16';
    });
}
Comments