Display rows of chosen items based on the specific value of their sub objects using AngularJs

The JSON provided below is being utilized It comprises an array of objects (branch) with sub-objects called "service". The goal is to display the branch name and its services, specifically those categorized as cream.

[
  {
    "b_sn": "1",
    "b_name": "Alambagh",
    "service": [
      {
        "i_sn": "1",
        "i_name": "Vanilla",
        "i_type": "cream",
        "i_detail": ""
      },
      {
        "i_sn": "2",
        "i_name": "Orange",
        "i_type": "candy",
        "i_detail": ""
      }
    ]
  },
  {
    "b_sn": "2",
    "b_name": "Aminabad",
    "service": [
      {
        "i_sn": "3",
        "i_name": "Butterscotch",
        "i_type": "cream",
        "i_detail": ""
      },
      {
        "i_sn": "4",
        "i_name": "Blueberry",
        "i_type": "cream",
        "i_detail": ""
      }
    ]
  },
  {
    "b_sn": "3",
    "b_name": "Hazratganj",
    "service": [
      {
        "i_sn": "1",
        "i_name": "Orange",
        "i_type": "candy",
        "i_detail": ""
      },
      {
        "i_sn": "2",
        "i_name": "Mango",
        "i_type": "candy",
        "i_detail": ""
      }
    ]
  }
]

The objective is to exhibit only the rows where i_type ="cream". If a branch (object) does not contain any sub-object labeled "cream", then its b_name should be excluded from the table.

Below is the HTML code snippet from the page:

<table>
  <tr>
    <th>SN.</th>
    <th>Branch Name</th>
    <th>Services</th>
  </tr>
  <tr data-ng-repeat="br in branches">
    <td>{{br.b_sn}}.</td>
    <td>{{br.b_name}}</td>
    <td>
      <table>
        <th></th>
        <tr data-ng-repeat="i in br.service">
          <td style="width:70%">{{i.i_sn}}. {{i.i_name}}</td>
          <td>{{i.detail}}</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

Answer №1

If a branch does not offer any services of type 'cream', you can create a function to filter all the services that branch provides, and if no service with the type 'cream' is found, then simply return false so that branch is not displayed.

Similarly, when it comes to services, you can manually inspect each service to determine if it falls under the 'cream' category. This way, only branches with 'cream' services and 'cream' type services will be printed out.

Here's an example:

<table>
   <tr>
     <th>SN.</th>
     <th>Branch Name</th>
     <th>Services</th>
   </tr>
   <tr ng-if="creamCheck(br)" data-ng-repeat="br in branches">
     <td>{{br.b_sn}}.</td>
     <td>{{br.b_name}}</td>
     <td>
        <table>
           <th></th>
           <tr ng-if="i.i_type==='cream'" data-ng-repeat="i in br.service">
             <td style="width:70%">{{i.i_sn}}. {{i.i_name}}</td>
             <td>{{i.detail}}</td>
           </tr>
        </table>
     </td>
   </tr>
</table>   

Don't forget to define the creamCheck function as well:

 $scope.creamCheck = function(branch)
    {
        var arr = ($filter('filter')(branch.service, { i_type: 'cream' }));
        if (arr.length>0) {
            return true;
        }
        else
            return false;
    }

This approach should help achieve the desired outcome.

Answer №2

Appreciate the assistance from everyone. I have successfully found the solution. Below is the code snippet for solving the mentioned problem.

    <div ng-app="myApp" ng-controller="myCtrl">

      <table class="table">
        <tr>
          <th>SN.</th>
          <th>Branch Name</th>
          <th>Services</th>
        </tr>
        <tr data-ng-repeat="br in branches | myFilter: {'key':key}">
          <td>{{br.b_sn}}.</td>
          <td>{{br.b_name}}</td>
          <td>
            <table>
              <tr data-ng-repeat="i in br.service|filter :{i_type:'cream'}">
                <td>{{i.i_sn}}. {{i.i_name}}</td>
                <td>{{i.detail}}</td>
              </tr>
            </table>
          </td>
        </tr>
      </table>

    </div>

    <script>
      var app = angular.module('myApp', []);
      app.filter('myFilter', function() {
        return function(json, input) {
          console.log(json, input);
          var new_json = [];
          for(var i=0; i<json.length; i++){
            var flag = false;
            for(var j=0; j<json[i].service.length; j++){
              if(json[i].service[j].i_type == input.key){
                flag = true;
                  break;
              }
              else{
                flag = false;

              }
            }
            if(flag){
              new_json.push(json[i]);
            }
          }
          return new_json;
        };
      });
      app.controller('myCtrl', function($scope) {
        $scope.key = "cream";
        $scope.branches = [
          {
            "b_sn": "1",
            "b_name": "Alambagh",
            "service": [
              {
                "i_sn": "1",
                "i_name": "Vanilla",
                "i_type": "cream",
                "i_detail": ""
              },
              {
                "i_sn": "2",
                "i_name": "Orange",
                "i_type": "candy",
                "i_detail": ""
              }
            ]
          },
          {
            "b_sn": "2",
            "b_name": "Aminabad",
            "service": [
              {
                "i_sn": "3",
                "i_name": "Butterscotch",
                "i_type": "cream",
                "i_detail": ""
              },
              {
                "i_sn": "4",
                "i_name": "Blueberry",
                "i_type": "cream",
                "i_detail": ""
              }
            ]
          },
          {
            "b_sn": "3",
            "b_name": "Hazratganj",
            "service": [
              {
                "i_sn": "1",
                "i_name": "Orange",
                "i_type": "candy",
                "i_detail": ""
              },
              {
                "i_sn": "2",
                "i_name": "Mango",
                "i_type": "candy",
                "i_detail": ""
              }
            ]
          }
        ];

      });
    </script>

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

The top choice for AngularJS: A trustworthy JSON viewer and editor module

Currently, I am working on enhancing my app by incorporating a json editor feature. I would appreciate any recommendations on which module you have experience with and believe is both stable and effective. The data I am working with is already in json for ...

Making a RESTful API call using JavaScript

Can someone help me with making a call to a REST API using JavaScript, Ajax, or jQuery? curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:password http://url -d "{\"name\": \"Marcus0.2\ ...

I have put in a lot of effort, but unfortunately, the JavaScript validation is still

<script> function checkInput() { var input1 = document.myform.ename.value; var input2 = document.myform.eid.value; if (input1 == "" || input1 == null) { alert("Please enter the user name"); } ...

Creating, customizing, and assigning values to data attributes in Draft-js blocks: A complete guide

My current setup involves a DraftJS editor displayed like this: <Editor editorState={this.state.editorState} handleKeyCommand={this.handleKeyCommand} onChange={this.onChange} placeholder="Write a tweet..." ref="editor" spellCheck={true} /&g ...

Refresh the data table using AJAX and JSON to update the information

I'm currently utilizing the Datatable plugin and aiming to refresh the table via ajax. Despite following the instructions mentioned here, my ajax return data is not being displayed in the table. Below is a snippet of my html code: <button type="bu ...

The React-Redux application encountered an error: Key "coins" does not have a corresponding reducer

I'm encountering some errors that I don't understand. Currently in the process of setting up my store, actions, and reducers. I have not triggered any dispatch yet. Expected Outcome The application should run smoothly without altering the Redu ...

invoking a JavaScript function with onClick

Every time I try deploying my code, an error is thrown saying: saveRows is not a function. Can anyone help me figure out what's going on? dataGrid.prototype = { display: function() { var self = this; var html = []; va ...

Could components be responsible for data initialization delays?

I am encountering an issue with initializing "elements" in COMPONENTS using data received from a web request. For example (in pseudo code): <elem elemOpts="$ctrl.elemOpts" /> ....... ctrl = this; ctrl.web_data = []; ctrl.elemOpts = { data : c ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

The functionality of create-react-app has been malfunctioning ever since the release of version 4.0.1. Is there a way to successfully remove the outdated version and

After running the command npx create-react-app ./ to create a React app, I encountered a warning message and the app was not created as expected. To resolve this issue, it is recommended to remove any global installs using one of the following commands: - ...

An elusive static image file goes unseen within the realm of node.js/express

I am encountering an issue with serving static files in Express on Node.js. When I request a .css file from the server, everything works fine. However, if I try to load an image such as a jpg or png, it just shows a blank white page without any error messa ...

What is the process for downloading a buffer file stored in memory using express.js?

Explanation: My goal is to create an express.js website that allows file uploads to be saved in a database for later user download. I plan on converting files such as .jar, .txt, and .json into buffer data for storage in MongoDB. However, after researching ...

Tips for adjusting the text color of input fields while scrolling down

I am currently working on my website which features a search box at the top of every page in white color. I am interested in changing the color of the search box to match the background color of each individual page. Each page has its own unique background ...

Ensure that Google Tag Manager (GTM) delays the pageview until the SPA URL title is available

I'm dealing with a React SPA that manages all the URL titles on the frontend, so the historyChange event registered on GTM captures the visited URLs along with their titles correctly. However, I've noticed that on the initial load of the SPA, su ...

Having difficulty specifying numerical entries only

I have been attempting to create an input field that only accepts numbers, but for some reason it still allows letters to be entered. Why is this happening? <input type="number" pattern="[0-9]" ...

Learn the step-by-step process of cropping and zooming an image using the react-image-crop

I am looking to implement zooming and cropping functionality for an image using react-image-crop instead of react-easy-crop. Currently, the cropping does not take into account the zoom level set by ReactCrop's scale property. I want to be able to zo ...

Exploring parameterized routing in Node.js and Express

I am currently facing an issue with my node.js API where I have two separate routes set up. One route is for retrieving user data by ID, while the other is a general user endpoint. Here are the routes: app.get('/api/v1/user/:userid', function (r ...

AngularJS - convey additional properties of the selected object during ng-change event

Is there a way to display other properties from the loaded json in a dropdown using ng-options? I would also like to pass the selected object's campaignType on ng-change. How can I achieve this? This is how my view currently looks: <div ng-app ...

Encountered an error during the installation of the [email protected] script while running 'node build.js'

Encountering an error message when I try to run npm install on my project. Below is more information about the issue: npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="234d4c47460e5042505063130d1a0d15">[email p ...

Guidelines for utilizing an image as a trigger for an if/else condition

I'm attempting to create a rock, paper, scissors-style game using jQuery. Here's how I envision it working: The player selects a picture by clicking on it, triggering the .click function. The computer then generates a random number between 1 an ...