Hey there! I have an array of objects and I want you to take a look at the code below. Within this array, I have three values: 'A', 'B', and 'C'. If the B value does not exist in Mumbai, I would like to push 0.
Plunker
// Check out the code snippet below
var c = angular.module('myApp', ['angular.filter'])
c.controller('myCtrl', function($scope, $filter) {
$scope.finalArray = [];
$scope.data = [{
"id": "1",
"place": "Mumbai",
"name": "A",
"value": "10"
}, {
"id": "4",
"place": "Mumbai",
"name": "B",
"value": "20"
}, {
"id": "4",
"place": "Delhi",
"name": "B",
"value": "77"
}, {
"id": "5",
"place": "Delhi",
"name": "C",
"value": "11"
}, {
"id": "6",
"place": "Banglore",
"name": "A",
"value": "14"
}, {
"id": "7",
"place": "Banglore",
"name": "C",
"value": "100"
},
{
"id": "3",
"place": "Delhi",
"name": "A",
"value": "30"
}]
$scope.finalArray = [];
$scope.stationName = [];
$scope.name = $filter('groupBy')($scope.data, 'name');
angular.forEach($scope.name, function(k, v) {
$scope.title = [];
$scope.count = [];
console.log(k, v);
$scope.title.push(v)
angular.forEach(k, function(key, value) {
$scope.count.push(key.value)
})
var obj = { name: $scope.title[0], data: $scope.count }
$scope.finalArray.push(obj);
});
console.log($scope.finalArray)
})
<!DOCTYPE html>
<html>
<head>
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0dfd6c4ddd0c39fdbc2f1809f869f81">[email protected]</a>" data-semver="1.7.0" src="https://code.angularjs.org/1.7.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.17/angular-filter.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
{{finalArray | json}}
</body>
</html>
Currently, the output is as follows:
[ { "name": "A", "data": [ "10", "30", "14" ] }, { "name": "B", "data": [ "20", "77" ] }, { "name": "C", "data": [ "11", "100" ] } ]
However, my desired output should be [{name :"A",data :[10 30 14]},{name : "B",data : [20,77,10]},{name : "C",data : [0,11,100]}]