AngularJS filters unique attribute value and get filtered counter
I have the following array:
items: [
{
id: "0",
name: "כיבוי אורות",
icon: "rooms_salon.svg",
type: "scenario",
status: 1
},
{
id: "1",
name: "הדלקת אורות",
icon: "rooms_salon.svg",
type: "scenario",
status: 1
},
{
id: "0",
name: "תנור מטבח",
icon: "rooms_salon.svg",
type: "heater",
status: 0
},
{
id: "1",
name: "מזגן מטבח",
icon: "rooms_salon.svg",
type: "ac",
status: 0
}]
I need to filter it to get only the unique item.type and the original item count for each type.
It takes a strong:
items: [
{
type: "scenario",
amount: 2
},
{
type: "heater",
amount: 1
},
{
type: "ac",
amount: 1
}
]
What would be the best way to do this?
PO: I need to filter it in the controller, not the ng-repeat.
Thank you, highlight
Avi
+3
source to share
2 answers
You are not filtering, you need to create a new array with the values you want.
or
created a computed filter value like this
function Ctrl($scope){
$scope.items = [
{
id: "0",
name: "כיבוי אורות",
icon: "rooms_salon.svg",
type: "scenario",
status: 1
},
{
id: "1",
name: "הדלקת אורות",
icon: "rooms_salon.svg",
type: "scenario",
status: 1
},
{
id: "0",
name: "תנור מטבח",
icon: "rooms_salon.svg",
type: "heater",
status: 0
},
{
id: "1",
name: "מזגן מטבח",
icon: "rooms_salon.svg",
type: "ac",
status: 0
}];
Object.defineProperty($scope, 'filtered', {
get: function(){
var list = {};
$scope.items.forEach(function (item) {
if (list[item.type] === undefined) {
list[item.type] = 1;
} else {
list[item.type] += 1;
}
});
var newItems = [];
Object.keys(list).forEach(function(key){
newItems.push({
type :key,
amount: list[key]
});
});
return newItems;
}
});
}
+2
source to share
You can use a module angular-filter
to group your items:
$scope.items = [
{
id: "0",
name: "כיבוי אורות",
icon: "rooms_salon.svg",
type: "scenario",
status: 1
},
{
id: "1",
name: "הדלקת אורות",
icon: "rooms_salon.svg",
type: "scenario",
status: 1
},
{
id: "0",
name: "תנור מטבח",
icon: "rooms_salon.svg",
type: "heater",
status: 0
},
{
id: "1",
name: "מזגן מטבח",
icon: "rooms_salon.svg",
type: "ac",
status: 0
}]
$scope.content = $filter('countBy')($scope.items,'type');
Here you have a working plunker
+11
source to share