Utilizing filters in Angular JS to traverse a multidimensional array object with nested response nodes

From an array of objects, I am trying to filter based on the response_id key. This key is nested within the response object. If I input 23764 and 23765, I want to retrieve Question objects that have AT LEAST 2 RESPONSES with those specific ids as the only ones in the array.

If I search with just 23764, I want to get Question objects with a response object containing that id as the only one in the array.

The current implementation I have looks something like this:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$filter) {
    
    $scope.data = [
    {
        "id": "1341",
        "question": "What about this chaneel?",
        "response": [
            {
                "response_id": "23764",
                "comment": "Every thing "
            },
            {
                "response_id": "23765",
                "comment": "No"
            },
            {
                "response_id": "23766",
                "comment": ".."
            }
            
        ]
    },
    {
        "id": "1342",
        "question": "What dislike about this chaneel?",
        "response": [
            {
                "response_id": "23764",
                "comment": "Nothing"
            },
            {
                "response_id": "23765",
                "comment": "No"
            },
            {
                "response_id": "23766",
                "comment": ".."
            }
        ]
    },
    {
        "id": "1343",
        "question": "What suggestion(s) this chaneel?",
        "response": [
            {
                "response_id": "23764",
                "comment": "Nothing "
            },
            {
                "response_id": "23765",
                "comment": "No"
            },
            {
                "response_id": "23766",
                "comment": ".."
            }
        ]
    }
  ];
  
  var res = ($filter('filter')($scope.data, {response:{response_id:'23764,23765'}}, true));
  console.log(res);
  
});
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

Desired Result

[
{
    "id": "1341",
    "question": "What about this chaneel?",
    "response": [
        {
            "response_id": "23764",
            "comment": "Every thing "
        },
        {
            "response_id": "23765",
            "comment": "No"
        }
    ]
},
{
    "id": "1342",
    "question": "What dislike about this chaneel?",
    "response": [
        {
            "response_id": "23764",
            "comment": "Nothing"
        },
        {
            "response_id": "23765",
            "comment": "No"
        }
    ]
},
{
    "id": "1343",
    "question": "What suggestion(s) this chaneel?",
    "response": [
        {
            "response_id": "23764",
            "comment": "Nothing "
        },
        {
            "response_id": "23765",
            "comment": "No"
        }
    ]
}
]

Answer №1

In order to filter with 23764,23765 and retrieve an array of all questions containing one response object with id 23764 AND one response object with id 23765, as the only response objects within the returned results nested response array, there are various ways to create a custom filter function for this purpose.

Below is an illustration of one such approach:

var myCustomFilter = function(dataCollection, selectedValues) {

  selectedValues = selectedValues.replace(' ', '').split(',');

  var filteredResults = [];

  dataCollection.forEach(function(question) {

    var matchingResponses = [];

    question.response.forEach(function(response) {

      if (selectedValues.indexOf(response.response_id) > -1) matchingResponses.push(response);
    });

    if (matchingResponses.length !== selectedValues.length) return;

    var clonedQuestion = angular.extend({}, question);

    clonedQuestion.response = matchingResponses;

    filteredResults.push(clonedQuestion);
  });

  return filteredResults;
};

var userSelectedValues = '23764, 23765';

var finalResult = myCustomFilter($scope.data, userSelectedValues);

It might be beneficial to include some checks for arguments and explore optimization strategies, but this should provide a starting point.

You may also need to adjust the logic depending on whether you require duplicates of the original data or references.

Check out a live demo here: http://plnkr.co/edit/r6a5qbw4JJ6Zc5eFopLT?p=preview

Answer №2

Here's a solution using the angular forEach loop to remove an object:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$filter) {
    
    $scope.data = [
    {
        "id": "1341",
        "question": "What about this chaneel?",
        "response": [
            {
                "response_id": "23764",
                "comment": "Every thing "
            },
            {
                "response_id": "237657",
                "comment": "No"
            },
            {
                "response_id": "23766",
                "comment": ".."
            }
            
        ]
    },
    {
        "id": "1342",
        "question": "What dislike about this chaneel?",
        "response": [
            {
                "response_id": "23764",
                "comment": "Nothing"
            },
            {
                "response_id": "23765",
                "comment": "No"
            },
            {
                "response_id": "23766",
                "comment": ".."
            }
        ]
    },
    {
        "id": "1343",
        "question": "What suggestion(s) this chaneel?",
        "response": [
            {
                "response_id": "23764",
                "comment": "Nothing "
            },
            {
                "response_id": "237654",
                "comment": "No"
            },
            {
                "response_id": "23766",
                "comment": ".."
            }
        ]
    }
  ];
   $scope.result = [];
  angular.forEach($scope.data,function(d){
      angular.forEach(d.response,function(res,index){
          if(res.response_id == "23766"){
            d.response.splice(index,1);
             console.log(d.response);
            }
        })
    })
//console.log($scope.data);
});
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <pre>{{data| json}}</pre>
  </div>

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

JavaScript parameter not found

I am currently working on a block type plugin for Moodle and encountering some difficulties with my JS code. Due to my limited knowledge in JS and JSON, I am having trouble identifying the issue at hand. My code includes a function that adds a custom actio ...

What is the best way to choose $(this) within a JavaScript expression inside a template literal?

Is it possible to use template literals in the append method and get the index of the row generated? I understand that calling "this" inside the function selects the specified selector passed as an argument. $(document).on('click', '.ad ...

No matter what I do, I can't seem to stop refreshing the page. I've attempted to prevent default, stop propagation, and even tried using

Below is the code I have written for a login page: import { useState } from "react"; import IsEmail from "isemail"; import { useRouter } from "next/router"; import m from "../library/magic-client"; import { useEffect ...

Formulate an array and filter out items that conclude with a colon

I have an array that needs filtering to remove all objects ending with a colon. Is there a simple way to do this, such as implementing it in the existing filter function? var ingredientsArray = ingredients.replace(/<strong>[\s\S]*?<&bso ...

Getting information from MySQL database with just HTML and JavaScript

Looking to securely access a MySQL database on my localhost using only HTML and JavaScript. No need for server-side scripting or web servers. Any tips on how to make this happen? ...

Is there a way to automatically populate textbox values using a MySQL query response when the dropdown selection is changed?

How can I make the fields customer_address, customer_city, customer_state, and customer_zip autofill upon changing the selection in the dropdown for customer_name? I've searched everywhere but cannot find a solution. Your assistance would be greatly ...

Localization support is working partially in a Node Express application that uses Handlebars for templating

Whenever I visit a URL with the ?lang=en query parameter, the English translation is never used. However, the Hungarian text changes work perfectly fine, displaying text to test on Hungarian in the default "hu" language without any issues. What could be ca ...

Strategies for structuring CoreData to manage intricate datasets

I am faced with the task of storing JSON data locally using CoreData, which is retrieved from an API call. The challenge lies in the complexity of the JSON structure, as it consists of a main Dictionary with 4 keys, each key containing further nested Dict ...

Implement a content editable div when clicked

How can I dynamically add a content editable div when a button is clicked? Online resources suggest creating a directive for this purpose. I have attempted to do so, but the following code is not functioning as expected: app.directive("addEditableDiv", ...

Adding parameters to TR or TDs in DataTables 1.10.5 via Ajax: A step-by-step guide

My goal is to dynamically load datatable data using AJAX and customize the rows and cells by adding parameters such as classes or 'data' attributes. The challenge lies in utilizing a PHP helper that generates JavaScript code, as shown below: $da ...

Achieve a clockwise rotation of an object back to its original position using Three.js

As a novice in the world of THREE.js, I am currently working on an animation that spins a 3D model around its Y axis. However, for my website project, I need to smoothly rotate it back to its original position within a span of 90 frames. Despite trying dif ...

The environmental variable remains undefined even after it has been established

I've been experimenting with setting my environment variable in the package.json file so that I can access it in my server.js file. Despite trying NODE_ENV=development, set NODE_ENV=development, cross-env NODE_ENV=development, and export NODE_ENV=deve ...

Issue encountered: Object is not functioning properly with Node.js AuthenticationExplanation: A TypeError occurred

As a newcomer to Stack Overflow, I am doing my best to ask this question clearly. I am currently following a tutorial step by step ( http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local ) but I encountered an issue after the thir ...

Unable to receive a response in React-Native after sending a post request

My current challenge involves sending a response back after successfully making a post request in react-native. Unfortunately, the response is not arriving as expected. router.route("/addUser").post((req, res) => { let name= req.body.name; connection ...

Utilizing JSON, HTML, and jQuery to create a dynamic cascading dropdown menu

Is there a way to dynamically populate a dropdown menu for states and cities using jQuery? I have a JSON file with the state-city mapping, how can I implement this? Here is an example of the JSON file: [ { "state":"Karnataka", "cities": ...

verification pop-up with ngDialog

I integrated ngDialog into my application and want to develop a versatile confirm modal that can be used for various messages. Here are my questions: 1- Is it advisable to create a directive with ngDialog capabilities for this purpose, and what should it ...

Ways to determine if content is visible within a div

My website contains a script that brings in content from an ad network and displays it within a div element. Unfortunately, this particular ad network only fills ads 80% of the time, leaving the remaining 20% of the time without any ads to display. This la ...

PHP is encountering a duplication issue with the JSON output

My current goal is to store the JSON return result into a TXT file. However, I am encountering an issue where each iteration in the array includes all previous numbers. For instance, the first iteration only takes the first number in the array $array_1, bu ...

Developing an HTML table dynamically with JavaScript and incorporating CRM data

I am currently working on my JavaScript file, attempting to create an HTML table. Within this entity's record list are fields such as contractid, name, and address. var filter = "?$select=*&$filter=_plus_franchisee_value eq " + serviceProviderID ...

Enhancing User Experience with AJAX Page Loading and Progress Tracker

I'm looking to create a jQuery AJAX page load with a progress bar displayed at the top. I came across a helpful example of what I have in mind here. Any tips on how to get started would be greatly appreciated. This will be implemented on a WordPress ...