Displayed all the objects in an array as a list using ng-repeat, with a checkbox for each value.
My goal is to filter the checkboxes and create a new JSON when clicking Apply Filter based on checked/unchecked values.
Current Approach
I attempted to store the selected and unselected checkboxes in the models scope object ($scope.models) by combining the filter name and its values.
(e.g. : data1(filter name)+1(value) = data11)
When apply filter is clicked, I iterate through the existing filters array, compare it with the model object, and add matching entries to a new array.
Apply Filter function
HTML
<li ng-repeat="(key, filter) in filters">
<a href="" data-target="#{{filter.name}}" data-toggle="collapse" aria-expanded="{{enableShow.indexOf(filter.name) > -1 ? true : false}}">
{{filter.name}}
</a>
<ul class="collapse list-unstyled" id="{{filter.name}}" ng-class="{show : enableShow.indexOf(filter.name) > -1}">
<li ng-repeat="v in filter.values">
<label class="w-100" ng-show="filter.type == 'CheckBox'">
<span class="ml-3 p-1 d-block">
{{v.value}}
<input type="checkbox" ng-model="models[filter.name + v.value]" class="pull-right mt-1 ml-1" style="margin-right: 7%" />
</span>
</label>
</li>
</ul>
JS
$scope.applyFilters = function() {
var arr = [];
_.map($scope.filters, function(d) {
_.map(d.values, function(v) {
var name = d.name + v.value;
for (key in $scope.models) {
if (key == name) {
arr.push({
name: d.name,
values: v
});
}
}
});
});
console.log(arr);
};
Desired Outcome
Upon clicking apply filter, I want to generate a new JSON containing only the selected values within their respective objects.
{
"results": [
{
"name": "data1",
"type": "CheckBox",
"values": [
{
"value": "1"
},
{
"value": "4"
}
]
},
{
"name": "data2",
"type": "CheckBox",
"values": [
{
"value": "1"
}
]
},
{
"name": "data5",
"type": "CheckBox",
"values": [
{
"value": "3"
}
]
},
{
"name": "data6",
"type": "CheckBox",
"values": [
{
"value": "2"
}
]
}
]
}
Thank you in advance.