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

Well, it appears that I am having trouble establishing a connection between the users in this chatting application

I'm encountering a problem with establishing a connection between two users. I have already installed express and socket.io, but for some reason, the message is not getting through to the receiver's end. The code seems to be running fine as I can ...

Thumbnail Option in the WordPress Media Uploader

Is it possible to add support for selecting image size (thumbnails) in the Media Library popup created using the wp.media() function in WordPress? I am currently using WordPress 4.5.2 and my code sample is as follows: wp.media.frames.selectFile=wp.media( ...

Calls to debounced functions are postponed, with all of them running once the waiting timer is complete

Utilizing the debounce function to create a real-time search feature. Researching more on debouncing from https://css-tricks.com/debouncing-throttling-explained-examples/, it seems like the function should control the number of calls made. In my scenario ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

jQuery - Enlarge Tree View to the level of the selected node

I am struggling to figure out how to expand the tree view up to a selected node level. If anyone has any ideas on how to accomplish this, please let me know. For instance, if we click on 'Parent d' in the 'Category list', I want to exp ...

When creating a new user with 'Add new user' function in AngularJS, the JSON data overrides the existing data instead of being added separately. This issue needs

I have recently started using AngularJS and encountered an issue when trying to send form data to a JSON file after clicking the 'Add New Member' button. The new JSON data overwrites the existing data, but I actually want it to be added after the ...

Steps for removing the label associated with an input field in an HTML form

I attempted to use JQuery and JavaScript in order to modify the CSS of a label to make it greyed out, but unfortunately I have not been able to achieve this. The label is positioned next to a checkbox, and although I am able to disable the checkbox, I hav ...

Transferring a list from MVC ViewBag to JavaScript

I have a situation where I am passing a list of users from my controller to the view using the ViewBag. Now, I also need to pass this same list to the JavaScript on the page. One way I thought of doing this is by iterating through the list with a foreach l ...

Uncovering the power of injected JavaScript objects within Protractor

Our application loads requirejs, which then loads angularjs and other javascript modules. I am curious if there is a way to access these LOADED modules (angularjs, javascript modules) in a Protractor test. It's important that we are able to retrieve t ...

Issue with Local Storage: Value not being saved, instead [object MouseEvent] being stored

I am truly grateful for the help from @zim as it allowed me to drastically simplify my code for 2 buttons that store true/false values locally. However, I am facing an issue where the button click is registering as [object MouseEvent] instead of True/False ...

Failure to Present Outcome on Screen

Seeking assistance! I attempted to create a mini loan eligibility web app using JavaScript, but encountered an issue where the displayed result did not match the expected outcome upon clicking the eligibility button. Here is the HTML and JavaScript Code I ...

Updating the list in React upon form submission without requiring a full page refresh

Currently, I have a list of data being displayed with a specific sort order in the textbox. Users are able to modify the order and upon clicking submit, the changes are saved in the database. The updated list will then be displayed in the new order upon pa ...

I'm looking to create a Vuex getter to retrieve data from the Google API documentation – can you help

Can someone help me figure out how to create a getter in Vuex store with flat data from the Google Docs API? My goal is to extract the textRun content and store it in an array because there will be multiple messages. Currently, I have hard coded this respo ...

Issue: ENOENT - The specified file or directory, './views/s.ejs', does not exist in Node.js Express

Encountering an error when attempting to render a file from the 'views' directory in the 'routes'. The specific error message is as follows: Error: Valid Login { [Error: ENOENT: no such file or directory, open './views/s ...

Fill a .js script with moustache.js

I need help with organizing some JavaScript code that needs to access server-side data. I want to keep this code in a separate .js file, but I'm having issues populating it with the necessary server information using moustache. Here is my current setu ...

Tips for arranging Intervals in sequence?

I've been developing a customized Pomodoro timer with user-defined work and rest times. In my Timer component, I have the following initial logic: useEffect(() => { start(3); start(timeData.workTime); start(timeData.restTime); }, []) c ...

What is the best method to send a HTTP request (specifically for scraping) to an Angular2 website?

I am attempting to utilize a node server to extract data from an angular2 application. However, the issue I am encountering is that the response I receive is just the index.js file, which essentially represents the "loading..." section of the webpage. My ...

Exploring Parameters to Customize Search Results in React

I am currently working on implementing a data filtering system based on user input. However, it seems that the data disappears whenever I enter something into the search box. Upon inspecting the dev tools, I can see that the query state is being saved pro ...

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

Using React for form validation

I'm facing a challenge while trying to develop a user registration form, especially when it comes to displaying form validation errors. Issues: 1) The input fails to post (via axios) to the database upon submission for inputs without errors. 2) The e ...