Ways to sort out chosen checkboxes in angularJS

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.

Plunker

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.

Answer №1

Use the _.map() function to iterate through the original data structure and transform it as required. Utilize _.filter() or _.reject() to eliminate sections that do not have selected values (plunker):

$scope.applyFilters = function() {
  var updatedArray = _($scope.filters)
    .map(function(obj, index) {
      var section = _.pick(obj, ['name', 'type']);

      section.values = _(obj.values)
        .filter(function(val, j) {
          return $scope.models['data' + (i + 1) + (j + 1)];
        })
        .map(_.partialRight(_.pick, 'value'))
        .value();

      return section;
    })
    .reject(function(obj) { return _.isEmpty(obj.values); })
    .value();

  console.log(updatedArray);
};

Answer №2

If you want to include only selected values in their respective object, you can utilize obj.hasOwnProperty(prop).

To achieve this, modify your applyFilters function like so:

 $scope.applyFilters = function() {
    var filteredArr = [];
    _.map($scope.filters, function(filter) {
      _.map(filter.values, function(value) {
        var name = filter.name + value.value;
        for (var key in $scope.models) {
           if (key == name && $scope.models.hasOwnProperty(key) && $scope.models[key]) {
            filteredArr.push({
              name: filter.name,
              values: value
            });
          }
        }
      });
    });
    console.log(filteredArr);
  };

Here is the updated plunker for reference:

I hope this solution proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the status of file() requests post-executionWould you like the status of file

I am working with an API public function airtime() { $send = file("https://www.example.com/APIQueryV1.aspUserID=CK123& APIKey=456&OrderID=789.............."); if($send) { return $status->ORDER_COMPLE ...

Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array: [ {"data": [ {"W":1,"A1":"123"}, {"W":1,"A1":"456"}, {"W":2,"A1":"4578"}, {"W":2,"A1":"2423"}, {"W":2,"A1":"2432"}, {"W":2,"A1":"24324" ...

What is the method to utilize global mixin methods within a TypeScript Vue component?

I am currently developing a Vue application using TypeScript. I have created a mixin (which can be found in global.mixin.js) and registered it using Vue.mixin() (as shown in main.ts). Content of global.mixin.js: import { mathHttp, engHttp } from '@/ ...

If a different link is selected, remove the class from the ID, and vice versa

I've been working on solving a jQuery issue that involves manipulating classes in a parent container with two divs and links. The goal is to add a class to change the background when a link is clicked in one div, and remove it if the other link is cli ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

Using an Angular route to trigger the resolution of data from a service

I'm having trouble figuring out how to implement Angular route resolve. The documentation does not provide much help for more complex aspects of the javascript framework like this. Here is the service I am using: app.service("AuthService", ["$http", ...

Dynamically loading a webpage with an element roster

I have a list and I want it so that when a user clicks on the sport1 list item, results from the database table sport1 will be displayed. Similarly, if they click on the education1 list item, results from the education1 table should be shown. The issue i ...

Can PHP send a response to Ajax following a 500 error?

While my AJAX function is successfully sending data to a PHP file and displaying the response in my HTML, I have encountered occasional Error 500 responses from the PHP file. Despite knowing the cause of the error, I continue to call the AJAX function agai ...

Is it possible to showcase two modals on a single page, positioning one to the left and the other to the right using Bootstrap?

Can someone help me learn how to display two modals on the same screen, one on the left and one on the right? I am new to bootstrap and would appreciate some guidance! ...

When using navigator.mediaDevices.getUserMedia on an iPhone, the webcam is activated in fullscreen mode

I'm facing an issue with the webcam functionality on my app. It works perfectly on Android and Windows, but when I try to use it on iPhone, the webcam opens in a separate full-screen view. Any ideas on how to resolve this? Thank you for your help in a ...

The latest Chrome update has caused a decrease in rendering and loading speeds for Ajax and Angular network

It has been around two weeks since a Chrome update caused trouble for users of my angular app. Previously, the entire single page application loaded in under 4 seconds, but after the update, every user was experiencing load times exceeding 40 seconds. Surp ...

A versatile JavaScript function built to efficiently validate numerous forms across a webpage

Sorry for the simple query, but I'm still learning JavaScript. I have a script that checks if a text field is empty to validate user inputs. If it's not empty, a confirmation window pops up before submitting the form and uploading the information ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...

Is it possible to define a Divider or Header within the options array for the dropdown component in Semantic UI React?

Currently, I'm incorporating ReactJS along with SemanticUI for ReactJS to enhance the appearance of my front end. My query pertains to whether it is feasible to define a header or divider within the options array of objects for a dropdown component? ...

In order to add value, it is necessary to insert it into the text box in HTML without using the "on

example <input type="text" id="txt1" onChange="calculateTotal();" /> <input type="text" id="txt2" onChange="calculateTotal();" /> <input type="text" id="txt3" onChange="updateValue();" readonly/> <input type="text" id="txt4" onChange= ...

Tips for using lodash to concatenate a string to an element in an array

My json object is structured like this: "data": [{ "firstName": "XYZ", "lastName": "Admin", "userId": 1, "companyLogo":"Logo" }, { "firstName": "ABC", "lastName": "Admin", "userId": 1, "companyLogo":"Logo1" }, { ...

Creating a Vue.js component that integrates a Bl.ocks.org graph

I'm a rookie in the world of D3 and I am trying to implement this cool d3 element into my Vue.js component. However, I've encountered an issue with the periodic rotation that I require not functioning properly. It seems to work initially but then ...

Deactivate the button once the form has been submitted

Seems like a simple and common question, right? I also thought so. How can I achieve this in angularJS? CSHTML @using (Html.BeginForm("Order", "Shop", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { <div class="container" ng-ap ...

Localizing Dates in JavaScript

I'm currently dealing with localization and globalization in an ASP.NET application. As I navigate through this process, I am encountering difficulties in getting the Date() function in JavaScript to function correctly based on the user's locatio ...

Functionality of jQuery Mobile Page

$(document).on("pageshow", "#mappage", function (event) { $("#doldur").append("<li> <label onclick='getBina(" + featuressokak[f].attributes.SOKAKID + ");'>" ...