Display unique values from multiple lists using AngularJS ng-repeat

I'm currently working on developing forms for our website using AngularJS. On the page, there will be two checkboxes labeled "Form 1" and "Form 2", with Form 1 being checked by default. When both Form 1 and Form 2 are checked, only distinct fields between them should be displayed.

Below is a snippet of my JSON data:

[
    {
        "form_id": 1,
        "form_name": "Form 1",
        "form_field_list": [
            {
                "form_field_id": 1,
                "form_field_label": "First Name",
                "form_field_value": ""
            },
            {
                "form_field_id": 2,
                "form_field_label": "Last Name",
                "form_field_value": ""
            },
            {
                "form_field_id": 3,
                "form_field_label": "Email",
                "form_field_value": ""
            }
        ]
    },
    {
        "form_id": 2,
        "form_name": "Form 2",
        "form_field_list": [
            {
                "form_field_id": 1,
                "form_field_label": "First Name",
                "form_field_value": ""
            },
            {
                "form_field_id": 2,
                "form_field_label": "Last Name",
                "form_field_value": ""
            },
            {
                "form_field_id": 4,
                "form_field_label": "Comments",
                "form_field_value": ""
            }
        ]
    }
]

For example, selecting "Form 1" checkbox should display the following input fields: First Name Last Name Email

If "Form 2" checkbox is selected, the following input fields should be displayed: First Name Comments

When both checkboxes are checked, these input fields should be displayed: First Name Last Name Email Comments

I'm uncertain about how to proceed. Should I create a separate JSON list first containing only unique form_field_list objects?

Answer №1

Here is a solution that should bring you closer to your desired outcome.

http://jsfiddle.net/v61ky2to/1/

var selectedFormFields = {};

$scope.uniqueFields = {};

$scope.toggleFormField = function(formField) {
  // Check if the field should be added or removed
  if (selectedFormFields[formField.form_id]) {
    delete(selectedFormFields[formField.form_id]);
  } else {
    selectedFormFields[formField.form_id] = formField.form_field_list;
  }

  // Update unique fields based on selected form fields
  $scope.uniqueFields = {};
  for (var i in selectedFormFields) {
    for (var j in selectedFormFields[i]) {
      $scope.uniqueFields[selectedFormFields[i][j].form_field_id] = selectedFormFields[i][j];
    }
  }
}

To achieve this, keep track of selected fields and consistently update child fields by concatenating them based on their unique form_field_id.

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

Adding a border to the <area> element: A step-by-step guide

Can a border be added around an <area> element? This would be useful for testing an imagemap, however the following code does not achieve the desired effect: area { outline: 1px solid red; border: 1px solid red; } ...

Click on the button to retrieve the data from the table cell

I have a table created using JavaScript <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">City</th> <th scope="col">Region</th> </tr> < ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

A valid json in mysql is causing an error due to a missing comma or '}' after an object member

I encountered the following error message: SQLSTATE[22032]: <<Unknown error>>: 3140 Invalid JSON text: "Missing a comma or '}' after an object member." at position 19 in value for column 'requests.calendar_attendee& ...

javascript conceal other sections upon hovering

There are 4 list items (<li>) that I want to use as triggers for linked images. In this project, I am using vanilla JavaScript as jQuery is not allowed. Below is the code snippet: var children = document.querySelectorAll('#resistorContent > ...

Count duplicated values in an array of objects using JavaScript ES6

I am working on creating a filter for my list of products to count all producers and display them as follows: Apple (3) I have managed to eliminate duplicates from the array: ["Apple", "Apple", "Apple"] using this helpful link: Get all non-unique values ...

Is there a way to extract JSON information from a Sequelize query result?

I have been working on a project that involves a handlebars app, router.get('/findBehavior/:student_id', async (req, res) => { console.log("---> req.params.student_id :" + JSON.stringify(req.params.student_id)); const stu ...

Sending extra arguments to routes in expressjs

As I delve into working with express, I've come across a puzzling obstacle: All of my route logic is stored in separate files and then included using require(route_name). The corresponding get/post matches are set up like this: app.get('/' ...

Tips for creating a VueJS method using JavaScript code?

Check out my codepen link here export default { data() { return { expanded: false, }; }, methods: { var checkList = document.getElementById('list1'); checkList.getElements ...

Executing a task after each scenario in protractor using selenium server and angularjs

Is there a way to perform an action after each describe block (not after each testcase) and before each describe? I am looking for a method similar to the afterEach block, can someone assist with this? ...

Limit the implementation of Angular Material's MomentDateAdapter to strictly within the confines of individual

Within my app, I have several components that utilize the mat-datepicker. However, there is one component where I specifically want to use the MomentDateAdapter. The issue arises when I provide it in this one component as it ends up affecting all the other ...

Issue with Node.js MongoDb query results in the retrieval of all documents instead of the specific

Example of Json Structure: {"address": {"building": "1007", "coord": [-73.856077, 40.848447], "street": "Morris Park Ave", "zipcode": "10462"}, "borough": "Bron ...

Searching for duplicated packages in npm

npm dedupe is known to simplify the folder structure, but I want to have a clear view of any duplicate packages before proceeding. Is there a way to generate a list of duplicate packages before running the command? If not, are there any scripts available ...

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

Anticipating a covert operative, but ended up with nothing?

Struggling to understand jasmine spies, here's how my test code looks: $scope.switchTurns = function () { $scope.playerTurn = !$scope.playerTurn; console.log($scope.centrePileCards.length); if ($scope.playerTurn == 1) { $scope.pic ...

When using Angular SSR, the transferState.get(key, null) method may return null even though objects are visible when logged (both in the browser)

While working on my Angular application, I've noticed a flicker when simulating a mid-tier mobile browser. It seems like Angular is not properly rehydrating the DOM when transitioning from Server to Browser, resulting in a full replace of the DOM. Th ...

Issue with Vue3 Button - property error not defined

I'm currently facing an issue with a button that isn't functioning as expected in the screenshot provided. I'm hopeful that someone can assist me with this. Button functionality The button itself is not clickable, but I am able to submit t ...

Ways to combine two arrays using dual requests in JavaScript with Mailchimp

The issue with the title not being very clear has been noted. Allow me to elaborate on my problem. Below is the code snippet: mailchimpMarketing = require("@mailchimp/mailchimp_marketing"); mailchimpMarketing.setConfig({ apiKey: "MY API KEY", server: "MY ...

Tips for adding strings into a JSON field in PostgreSQL

I've been facing difficulties when trying to insert data into a table in PostgreSQL that has a JSON column... The issue arises when I try to extract a bit column from another table and then insert it into the JSON column. Here's an example of wha ...

Create a React application that features a countdown timer using the new Date()

I have attempted to create a countdown timer, but I am encountering a problem with the getTime() function. This function calculates the remaining time by subtracting the current time from the finish time. However, the function is called multiple times ever ...