Filtering an object using data in AngularJS

My current data object structure looks like this :

$scope.data =  [
      {
        "name": "1001",
        "queue": [
          {
            "number": "111",
          }
        ]
      },
      {
        "name": "1002",
        "queue": [

        ]
      },
      {
        "name": "1008",
        "queue": [
          {
            "number": "222",
          }
        ]
      }]

In my AngularJS project, I have initialized 3 empty arrays:

$scope.a = [];
$scope.b = [];
$scope.c = [];

The desired outcome that I am aiming for :

If I were to execute console.log($scope.a);, the expected output would be :

{
    "name": "1001",
    "queue": [
      {
        "number": "111",
      }
    ]
  }

If I were to execute console.log($scope.b);, the expected output should be :

{
    "name": "1008",
    "queue": [
      {
        "number": "222",
      }
    ]
  }

And if I were to execute console.log($scope.c);, then the anticipated result should be :

{
    "name": "1002",
    "queue": [

    ]
  }

I am seeking a way to iterate through the data and based on the values in the queue array, push objects into different arrays. Specifically, I want to push objects with queue number "111" into $scope.a, objects with queue number "222" into $scope.b, and objects with an empty queue array into $scope.c. I am currently stuck on how to filter these objects by examining the values within the queue array. Can someone guide me on how to achieve this in AngularJS?

Answer №1

If you're facing this issue, @Navin, the solution is rather straightforward. Simply iterate through the array of objects and compare the queue number in each object. Once you find a match, add it to the respective array.

Below is an example of the code snippet that works:

var data = [{
    "name": "1001",
    "queue": [{
      "number": "111",
    }]
  },
  {
    "name": "1002",
    "queue": [

    ]
  },
  {
    "name": "1008",
    "queue": [{
      "number": "222",
    }]
  }
];
var a = [];
var b = [];
var c = [];
for (i = 0; i < data.length; i++) {
  if (data[i].queue.length != 0) {
    for (j = 0; j < data[i].queue.length; j++) {
      if (data[i].queue[j].number == 111) {

        a.push(data[i]);
      } else if (data[i].queue[j].number == 222) {
        b.push(data[i]);
      }
    }
  } else {
    c.push(data[i]);
  }
}
a = JSON.stringify(a);
b = JSON.stringify(b);
c = JSON.stringify(c);
console.log(a + "\n" + b + "\n" + c);

Answer №2

One way to achieve this is by using a for loop with the $scope.data object array.

for(i=0; i<=$scope.data.length; i++){
   if($scope.data[i].queue.length != 0){
       for(j=0; j<=$scope.data[i].queue.length; j++){
         if($scope.data[i].queue[j].number == 111){
               $scope.a.push = $scope.data[i]
           }else if($scope.data[i].queue[j].number == 222){
                      $scope.b.push = $scope.data[i]    
                   }
        }
    } else {
             $scope.c.push = $scope.data[i];
           }
 }

This method can potentially solve your problem. Give it a try!

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

Tips for organizing the items in an array in a specific order

Seeking advice on sorting array objects in JavaScript based on input sequence. Given an array input [abc, xyz, 123], the output array object looks like: [ { "label" : "positive", "id" : "abc" }, { "label" : "positive", "id" : "xyz" }, { "label" : "negativ ...

Animate play in reverse with JavaScript upon mouse exit

I'm currently using a code that works really well, but there's one thing I'd like to improve. When the mouse leaves, the animation stops abruptly which doesn't provide a great user experience. I have a few ideas: How can I make the &a ...

Choose values from an array to act as foreign keys to join multiple tables

In the table depicted below table CREATE TABLE IF NOT EXISTS "Article"( "ArticleId" SERIAL NOT NULL, "GenresIdList" integer[], ... PRIMARY KEY ("ArticleId") ); CREATE TABLE IF NOT EXISTS "Tag0"( "TagId" SERIAL NOT NULL, "Name" varchar, ... PRIMARY K ...

What is the best way to insert a newline in a shell_exec command in PHP

I need assistance with executing a node.js file using PHP. My goal is to achieve the following in PHP: C:proj> node main.js text="This is some text. >> some more text in next line" This is my PHP script: shell_exec('node C:\pr ...

Transferring live data between AJAX-triggered pop-up windows

Utilizing modals frequently in my application is a common practice. There are instances where I need to transfer data from one modal box to another. For instance: Suppose there is a table listing different car manufacturers (Audi, BMW, Honda, etc). Each r ...

Stopping multiple queries in Node.js can be achieved by using proper error handling

Upon verifying the existence of the name, the program continues to the subsequent query and proceeds with inserting data, which results in an error due to multiple responses being sent. How can I modify it to halt execution after checking if (results.row ...

Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code import NavLayout from "../../components/Navigation/Navigation"; export default function WorldOfWarcraft({ game }) { return (<NavLayout> {game.link} </NavLayout>) } WorldOfWarcraft.getInitialProps = as ...

Is there a way to prevent Backbone.js from deleting surrounding elements with 'default' values?

Trying to articulate this question is a challenge, so please let me know if further clarification is needed. As I am new to backbone.js, my inquiry may seem basic. My goal is to utilize backbone to efficiently generate graphs using the highcharts library. ...

Troubleshooting ASP.NET: Resolving a 404 Error when Trying to Retrieve

Attempting to execute a sample program provided by EditableGrid on my localhost with asp.net. Specifically, it involves loading json data. An error is thrown that reads: GET http://localhost:60218/grid.json?22895 404 (Not Found) The issue occurs at this ...

The distinction lies in whether the function is called directly within the ng-click attribute or is delayed until after the DOM has

Having an issue with AngularJS, I wanted to inquire about the difference between these two methods: angular.element(document).ready(function () { $scope.callFunction(); }); and <a href="#" ng-click="callFunction()"></a> When modifying a ...

Developing a string array based on user input in the C programming language

I recently encountered an issue while trying to create an array from user input in C. The code I used is as follows: #include <stdio.h> #include <stdlib.h> char** create_dynamic_array(int size); int main(){ char** myArray; int i; ...

Can we prevent a component from being mounted every time it is rendered by its parent component?

Is it possible to render the Child component within the Father component without mounting it and resetting its states when the Father component is rendered? I attempted to use the useMemo hook to render the Child component, but it still mounts the compone ...

Utilizing AngularJS to Incorporate CSV Data into SVG Illustrations

My latest project involves creating a floor plan application for my company using SVG floor plan drawings from Adobe Illustrator CC, along with HTML, CSS, and AngularJS. The goal is to combine a floor plan with static cubicle/office numbers with a CSV fil ...

Tips for organizing command line arguments within an array function

Could someone assist me in creating a class that includes a setter to assign values to an array? In the main method, I would like to take command line arguments and use the method to populate the array. I am unsure of how to proceed with this task and any ...

Compare an integer variable with numbers that have been previously saved in an array

Just dipping my toes into the world of coding, I have basic skills in Java and am eager to learn more on my own and from others. Not currently enrolled in university. Hey there! I'm attempting to create an array with a small capacity (5 integers) to ...

Techniques for retrieving the text content of a child span element based on the name of a neighboring element with

Currently, I am dynamically and uniquely binding the dropdown name. However, I am encountering an issue when attempting to retrieve the text of a span by using the neighboring or main dropdown name within the following div. <div class="SumoSelect" tabi ...

Tips on transferring large JSON data (250kb) to a MySQL database through the use of AJAX, JavaScript, and PHP

function sendProjectData(docsId, data) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { localStorage.setItem('updatedData',JSON.stringify(data)); if (this.readyState == 4 && this.sta ...

Steps for incorporating monaco-editor into a website without utilizing nodejs and electron

Currently, I am working on building a basic web editor and came across Monaco-editor. I noticed someone using it with Electron, but I am interested in integrating it into plain JavaScript just like on their webpage (link). However, I am struggling to fin ...

Do you always need to use $scope when defining a method in Angular?

Is it always necessary to set a method to the $scope in order for it to be visible or accessible in various parts of an application? For example, is it a good practice to use $scope when defining a method that may only be used within one controller? Consid ...

Show and hide elements using jQuery's toggle functionality

Here is some HTML code that I have: <div id="text-slide"><ul class="menu"> <li><a href="" id="toggle1">Webdesign</a> </li><div class="toggle1" style="display:none;width:45%; position:absolute;left: 16%; top:0;"> ...