How do I efficiently filter a nested object in AngularJS?

I need help filtering a nested object in AngularJS. I have created a function to retrieve the proptypes, and now I want to filter out objects where type1.value = false.

JSON:

scope.States = {
  "1": {
    "Prop": {
      "id": 1
    },
    "PropTypes": {
      "Type1": {
        "date": "2015-05-30T01:01:04",
        "value": false,
        "id": 1,
        "name": "defautPompier"
      },
      "Type2": {
        "date": "2015-05-30T01:01:04",
        "value": true,
        "id": 1,
        "name": "Delestage"
      }
    },
    "defaultsInstallations": ["defautPompier", "Delestage"]
  }
}

Controller:

$scope.GetDefaultByInstallation = function(title) {
    $scope.installationsStates = [];
    var res;
    $scope.result = [];
    Object.keys($scope.States).forEach(function(key) {
          var res = false;
          angular.forEach($scope.States[key].PropTypes, function(value, cle) {
                if ($scope.States[key].PropTypes[cle] == title) {
                  res = true;
                }
              }

Answer №1

When it comes to filtering data, there are two primary methods you can use:

  1. Filtering inside the HTML
  2. Implementing a filter function within controllers

According to the documentation

{{ expression [| filter_name[:parameter_value] ... ] }}

By using the "pipe" symbol in your code, you have the ability to add filters.

For example:

<ul>
  <li ng-repeat="friend in person.friends | startsWithA">
    {{ friend }}
  </li>
</ul>

In JavaScript:

app.filter('startsWithA', function () {
  return function (items) {
    var filtered = [];
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      // ... logic for filtering items
      // E.G.
      if (/a/i.test(item.name.substring(0, 1))) {
        filtered.push(item);
      }
    }
    return filtered;
  };
});

You also have the option to filter your data within a controller (ensuring you add a new filtered list to the scope) and then use this filtered list within the ng-repeat.

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

ng-if not behaving as anticipated

My angular expression is {{ userInfo.activities.ids }}, which is an array passed to Angular through PHP. I need to check a specific value in this array using the following code: [[userInfo.activities.ids.indexOf(1) != -1]], which returns either true or ...

Error encountered when attempting to use setInterval: '$' not located

I'm attempting to programmatically click a button as soon as it's created, and then close the interval. However, I'm encountering an error that says $ is not defined when running the script below. Can someone assist me in identifying where m ...

React Select Event Bug: Not firing on subsequent attempts

My select filter menu has 5 different options that work fine when the page loads or refreshes. However, when I try to continuously select an option, it does not filter the content as expected. Here is a snippet of the code: <div className="filter_ ...

Is it possible to include a callback function or statement following a $timeout in AngularJS?

function fadeAlertMessage() { $scope.alertMessagePopUp = true; $timeout(function() { $scope.fade = true; }, 5000) function() { $scope.alertMessagePopUp = false; } I'm facing a challenge and I'm seeking assistance with this is ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

What is the process for obtaining the indirect link of a Google search result?

I am looking to obtain the indirect link of a Google search result. After performing a search on Google, if I right-click on the result link, it changes to something like this: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&am ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

The function toDataURL() in Canvas is storing images in low resolution

I created a unique polygonal background generator using HTML5 canvas which can be found at the following link: http://codepen.io/rfalor/pen/LhinJ Here is the important part of the code: var canvas = document.getElementById("canvas"); var ctx = c ...

Prevent the left border from displaying on a link that wraps to a new line

Excuse me, I am facing an issue with a pipe separator in my subnav bar between links. The problem is that the first link on a new line retains the left-border that should be disabled. How can I prevent this border from appearing on the first link of a new ...

Exporting the Matter.js engine world data to JSON format

Is there a way to save my engine.world Object in an exportable format? I attempted converting it to a JSON string using JSON.stringify(engine.world) but encountered issues with the circular structure. Are there any solutions for this problem, or alternativ ...

Looking to dynamically modify the preselected rows in an Angular Slickgrid grid option when a button is clicked by calling a function (check)

When the button is clicked, certain specific rows are selected using a preselected grid option in Angular Slickgrid. However, if I do this, the preselected row in the grid options changes but it does not display properly. Please assist me. Typescript File ...

Detect When the Browser on a Mobile Device is Closed

I've been searching for a solution to detect when a mobile browser is closed so I can delete a cookie. I tried using window.onbeforeunload and window.unload, but they don't seem to work on mobile browsers. Despite my efforts in researching online ...

Troubleshooting: Discord bot failing to initialize on Heroku

After successfully hosting my bot on Heroku for a while, I temporarily switched back to self-hosting to update to discord.js v13. Now that I'm done with the updates and trying to re-host the bot on Heroku, I'm encountering this error: (node:4) Un ...

Angular component experiencing difficulty sorting a column sent from parent component to child component

I'm currently facing an obstacle while trying to pass a column from a parent component to a child component in Angular. The issue arises when attempting to sort the column. Below is the code snippet: Parent component <table-sorting-example matSort ...

Keep the sub-menu in a kendo context menu from closing until the user either hovers over another menu item or clicks outside of the current item

Please take a look at this example: Due to the small size of sub-items, the sub-menu closes quickly when hovering over the menu and losing focus. My goal is to keep an opened sub-menu from closing until the user hovers over another menu item or clicks on ...

Utilizing JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

Create a system where three arrays are interconnected, with the first array representing the name of the object

I have a group of different objects structured like this: let object1 = { xyz: 'xyz1', arr: [] }, object2 = { xyz: 'xyz2', arr: [] }, object3 = { xyz: 'xyz3', arr: [] } Manag ...

The DXTreeview feature in AngularJS restricts the expansion of branches

My MVC5 project contains an Index.aspx file, but when I run it in VS2013, only the top branches of the tree are visible without any option to expand them. https://i.sstatic.net/0FWUB.png Resharper confirms that my references are correct. Being new to HT ...

Expanding an array in JavaScript

I need assistance with... let a = ['a', 2, 3]; a += function(){return 'abc'}; console.log(a[3]); Therefore, I am looking for a shorthand method to push() in array with the above content. Does anyone know of an operator that can help ...

Struggling with making JSON.parse() function properly in a Discord Bot

I have a separate JSON file connected like this const Players = require('./Database/Players.json'); and a parser that handles the code client.on('message', message => { if (message.content.toLowerCase() ==='smack activate ...