Angular connecting to the count of filtered items

Here's the array I'm working with:

[
    {
      type: "hhh",
      items: [
        {
          "name": "EGFR",
          "type": "a",
          "selected": true
        }
      ]
    },
    {
      type: "aaa",
      items: [
        {
          "name": "mm",
          "type": "b",
          "selected": false
        }
      ]
    },
    {
      type: "ii",
      items: [
        {
          "name": "pp",
          "type": "bb",
          "selected": true
        }
      ]
    }
  ]

I'd like to display a counter that shows the number of items with the selected property set to "true". I want it to update in real time without using watch or functions.

Thanks!

Answer №1

Follow this method:

let selectedCount = {
  get total(){
    let count = 0;
    itemsArray.forEach(function(item, index, array) {
      if (item.items[0].selected) count++;
    })
    return count;
  }
}

Usage example:

selectedCount.total

Demo

Answer №2

To retrieve the count, JsonPath can be utilized effectively. One of the benefits of using JsonPath is its capability to navigate through complex json structures effortlessly. For your specific scenario, simply import the jsonpath.js file and incorporate the following code snippet into your script:

console.log(arr);
var filtered = jsonPath(arr, "$.[*].items[?(@.selected==true)]");
console.log(filtered);
console.log(filtered.length);

In this code snippet, 'arr' represents your json structure.

The latest version of JsonPath can be obtained from: https://code.google.com/archive/p/jsonpath/downloads

For further assistance with JsonPath, refer to:

While there may be newer versions available elsewhere, the one mentioned here is the one I have personally used in my projects.

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

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

How to Send a Multi-part Message Using AT Commands and PDU Mode in Node.js

I am trying to send a multipart message using AT commands. Single parts work fine, as do special characters. However, when the message exceeds 160 characters, it shows as sent but nothing is received. const async sendSMS(msisdn, message) { message += ...

How should one correctly trigger an event in Google scripts?

When it comes to calling in the active elements, I have been using event.source.getActive and SpreadsheetApp.getActive. However, I have noticed that I sometimes interchange them in my script and face issues. So, I am unsure about which method is more app ...

Is it possible to invoke the function `this.function` within the same file where it is declared?

During our project, we set out to develop a Protractor framework. In the JavaScript file, we created some functions using the 'this.functionname' syntax with the intention of reusing these functions when needed within the same file. For better cl ...

Can someone explain how to replicate the jQuery .css function using native JavaScript?

When referencing an external CSS file, the code may look something like this: #externalClass { font-family: arial; } Within the HTML file, you would use it like so: <a href="#" id="externalClass">Link</a> In the JavaScript file, you can ret ...

Triggering an event in the browser that bubbles up through the DOM

I'm currently attempting to utilize the browserTrigger() method on an element and I require the event to bubble up to its ancestors. However, the handler from the ancestor element is not triggering. To illustrate my issue, here's a simple exampl ...

Include the aria-labelledby attribute in the jQuery Datatable Pagination

Check out the HTML output created by the Jquery Datatable plug-in for pagination(https://datatables.net/plug-ins/pagination/full_numbers_no_ellipses): <div class="dataTables_paginate paging_full_numbers" id="my-table_paginate" aria-l ...

Convert a list to a JSON object utilizing the Json.NET library

I am using json.net to convert currency rates to JSON format. In the C# entity, there are Name and Value properties; where Name represents currencies like USD, GBP, etc. and Value holds the currency rate. Since I do not know the index of different curren ...

Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". H ...

The functionality of the custom file upload button is experiencing issues on Microsoft Edge

I've been working on creating a unique custom image upload button that functions perfectly in Chrome, Firefox, and Opera based on my testing. However, I'm facing an issue where it doesn't work properly in Microsoft Edge. Feel free to check ...

What is the proper way to display the complete result of aggregating each outcome from the previous iteration within two nested queries in an array using NodeJS and Mongoose?

As a newcomer to both Stackoverflow and NodeJS/Mongoose, I apologize if I make any mistakes or break any rules. Thank you in advance. I'm looking for a function that can return all nearby products based on my current location, which is provided by th ...

Adjust the height of each child element to be half of the fixed height of the parent

There is a wrapper containing multiple boxes generated using ng-repeat from a list. The wrapper has a fixed height of 300px. If the list contains only one box, a class is added to fill the entire space of the wrapper. However, when there are more than on ...

Prevent the onscroll animation of the SVG from activating immediately upon its appearance on the screen

I am in the process of building a website that incorporates SVG technology. My issue is with some SVG icons that have animated effects when scrolling, but the animation triggers as soon as they come into view. What I really need is for these icons to sta ...

Is there anything else I should attempt in order to fix this npm start error?

I have been troubleshooting this issue by researching other stack overflow posts, but I continue to encounter the same error message repeatedly. My goal is to execute a Javascript program that incorporates ReactJS. Initially, everything was functioning sm ...

Cookie vanished post registration in the captive portal

Just a heads up, I'm new to this. I've encountered an issue where a cookie doesn't persist after captive portal login. The setup involves landing on our web server, storing MAC and a unique ID on two cookies, redirecting for authentication, ...

Avoid loading the page when the browser's back button is pressed with vue-router

In my application, I have a "Home" page as well as a "Success" page. On the Success page, there is a button that, when clicked, redirects to a URL like https://google.com, using window.location.href='https://google.com'. Currently, I am able to ...

JavaScript button click changes the selected row's color in a DataTable

I am looking to dynamically change the color of a row in my Datatable when a specific button is clicked. Here is the HTML code snippet for the rows: <tr role="row" class="odd"></tr> <tr role="row" class="even selected"></tr> & ...

Learn how to integrate ES6 features into your nodejs/expressjs application using either Gulp or Webpack

I am looking to incorporate ES6 features into my nodejs/expressjs application. Currently, I am using Gulp for JavaScript compilation and setting up live reload. What steps do I need to take in order to compile the es6 code to standard js within my exis ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...