Filtering a JSON object array with a nested array contained within

Within my object array, I am currently filtering against the property name "username" using the following code snippet:

array =   [{
    "id": 1,
    "username": "admin",
    "roles": [{
            "name": "Administrator"
        },
        {
            "name": "agent"
        }
    ]
},
{
    "id": 2,
    "username": "admin2",
    "roles": [{
            "name": "Administrator2"
        },
        {
            "name": "agent2"
        }
    ]
},
{
    "id": 3,
    "username": "admin3",
    "roles": [{
            "name": "Administrator3"
        },
        {
            "name": "agent3"
        }
      ]
    }
  ]

The filtering function looks like this:

  transform(array: any, valueToSearch: string): any[] {

      return array.filter(e => 
       e.username.toLowerCase().indexOf(valueToSearch.toLowerCase()) 
       !== -1);

     }

While this setup is functioning correctly, I now need to filter against the property name "name" within the "roles" array of each object. For example, I want to retrieve an object where the "roles" array contains a role with the name "agent3". This should return the last object in my example. I attempted the following approach:

return agents.filter(e => e.roles.filter(ee => 
       ee.valueToSearch.toLowerCase()) !== -1));

However, this method did not yield the desired results.

Here is a demonstration of the issue: https://stackblitz.com/edit/angular-txchxs?embed=1&file=src/app/agentFilter.pipe.ts

Answer №1

After reviewing your question and the provided example, I have modified your existing function to meet your requirements.

  ngOnInit() {
    this.updateArrayValues(this.array,'agent3');
  }

  updateArrayValues(array: any, valueToSearch: string): any[] {
    return  this.array.filter(e => {
        e.roles.filter(ee => {
          if(ee.name.toLowerCase() === valueToSearch.toLowerCase() ) {
            console.log(e);
            this.finalResult = e;
          }
        })
      })
  }

You can see the updated code in action on Stackblitz: https://stackblitz.com/edit/angular-uzgni7

Answer №2

sampleArray =   [{
    "id": 1,
    "name": "John Doe",
    "skills": [{
            "type": "Programming"
        },
        {
            "type": "Design"
        }
    ]
},
{
    "id": 2,
    "name": "Jane Smith",
    "skills": [{
            "type": "Marketing"
        },
        {
            "type": "Writing"
        }
    ]
},
{
    "id": 3,
    "name": "Tom Johnson",
    "skills": [{
            "type": "Finance"
        },
        {
            "type": "Data Analysis"
        }
      ]
    }
  ];
  

function searchFunction(){
    var filteredResults = sampleArray.filter((obj)=>{
        return obj.name.match(new RegExp(document.getElementById('search').value,'ig'));
    });
    console.log(filteredResults);
};
<input type="text" id="search" onkeyup="searchFunction()"/>

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

Is there a more streamlined approach to coding in PHP and jQuery?

My PHP script: <?php $data = file_get_contents('http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml'); $xml = simplexml_load_string($data); $data1 = file_get_contents('http://www.skysports.com/rss/0,20514,11661,00.xml ...

Output the label text from a NSDictionary containing a JSON object

Here is the structure of my JSON file: [{"id":"1","category":"New Category1","title":"New Product2","description":"Please type a description1","imgurl":"http:\/\/s.wordpress.org\/about\/images\/wordpress-logo-notext-bg.png","spect ...

Decoding JSON data from the Twitch API

I am currently working on retrieving a user's Twitch name using json_decode and their Steam ID, but I keep encountering an error that I can't seem to resolve. Despite researching similar issues faced by other users, I haven't made any progre ...

Exploring Python's Ability to Parse a JSON File Containing Multiple Objects

I'm struggling with programming in Python and feeling a bit lost. Despite reading through previous questions for an answer, I haven't been able to find a solution. My issue lies in trying to parse a JSON file containing approximately 1 billion ...

JSON in template form: remains unchanged

When working with a JSON file as a template and modifying properties, I encountered an issue where the variable activejson was not pulling fresh data from the template in each iteration of a loop. It seemed to retain old, modified values instead. My atte ...

xamarin.forms - Newtonsoft.Json.JsonSerializationException: Value conversion error occurred

As someone who is new to Xamarin.Forms, I've been working on deserializing a JSON string in order to display it in a listview. I managed to retrieve the JSON string from the server successfully, but encountered an error during deserialization: Newton ...

Error encountered in Angular/Ramda while using mapAccum with an array of objects in Typescript

I am having difficulties implementing Ramda in an Angular 6 / TypeScript environment. "ramda": "^0.25.0", "@types/ramda": "^0.25.24" This is how I have started: const addP = (p1,p2) => ({ x: p1.x+p2.x,y: p1.y+p2.y }); const accum = (a,b) => [add ...

Issue with Angular 6: Unable to match nested routes

I am working on a project to test nested routing in Angular. While the app-routes are functioning correctly, I am encountering an error stating that the children "cannot match any routes". After checking other solutions, I am still confused due to version ...

Using AngularFire to Showcase Firestore Key-Value Pairs in Collection Query

I have been working with a typical AngularFire collection query, but recently I received a project requirement that calls for a different approach. Instead of directly binding firestore nodes and values in the HTML, I need to bind the returned key and valu ...

Exploring a Java application

Currently, I am attempting to comprehend a Java program. This particular line of code is what I am focusing on: String[] words = line.split(" "); Will this code also separate the ';' from the variable name appearing before it? For instance: ...

Encountering a problem when trying to transform API data into a Pandas DataFrame

Below is the API output that I have: reponse.text '{"position": {"lat": 1.352083, "lon": 103.819836}, "mapView": {"N": 1.4784001, "E": 104.0945001, "S": 1.1496, "W": 103.594}}\n' My goal is to convert this output into a pandas dataframe. ...

Encountered an issue while trying to open the appointment editor in Angular Syncfusion Schedule - Getting an error message saying "Cannot read property '0

Utilizing the Syncfusion Angular schedule and looking to add a template for header quick information. https://i.stack.imgur.com/KI1Ie.png <ng-template #quickInfoTemplatesHeader let-data> <div *ngIf="data.elementTy ...

"Utilize React input event handler for enforcing minimum input

Is there a way to validate the minimum length of an input without submitting the form using the onKeyDown event? I've attempted to do so, but it seems to ignore the minLength property. I have a simple input field that doesn't need a form. Here&ap ...

Exploring the Maximum Subarray problem by considering alternative strategies to the running sum approach

While reviewing the Maximum Subarray problem on Leetcode #53, I stumbled upon a solution in the comments that I found interesting. I decided to adapt my code accordingly, but there's one aspect of it that I'm struggling to comprehend. Can someone ...

Creating a Schema for Group Entities (Comprising Multiple Users) in Mongoose

On my website, users have the option to join groups by entering a specific code, similar to games like 'Kahoot' or 'Psych'. For instance, I generate a unique 3-word code such as 'absent agitated alive', which users can input i ...

Shorten all the strings in a list using JOLT Conversion

I am attempting to trim strings in an array using JOLT. If a string starts with the character "^", I want to remove it. Here is the Sample Input: { "scores": [ "^aaaa", "^bbbb", "cccc", "^dddd ...

Creating a function in Typescript to extend a generic builder type with new methods

Looking to address the warnings associated with buildChainableHTML. Check out this TS Playground Link Is there a way to both: a) Address the language server's concerns without resorting to workarounds (such as !,as, ?)? b) Dodge using type HTMLChain ...

Exploring an array in React using typescript

I have a persistent data structure that I'm serving from the API route of my Next.js project. It consists of an array of objects with the following properties: export interface Case { id: string; title: string; participants: string[]; courtDat ...

JSON Countdown will pause when it reaches 0 days

I recently discovered a fantastic countdown feature in SharePoint that I'm utilizing to track the days until a specific date. I have created a calculated column that adds the current date with a set number of days for each task deadline. Currently, th ...

An error occurred due to attempting to access properties of null while trying to read 'useMemo' in a Next.js TypeScript application

Currently engaged in a Next.js 13 project with TypeScript, utilizing the useDrag hook. No errors are being flagged in my Visual Studio Code editor; however, upon attempting to render the page, an error message surfaces. The issue points to a problem with t ...