Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query:

Excuse me, I am new to Typescipt & RxJS. I have this JSON data:

[
{
    "ID": "",
    "UEN": "",
    "Name": "",
    "Address": "",
    "Telephone": "",
    "Fax": "",
    "Email": "",
    "Website": "",
    "Postal": "",
    "Status": ,
    "TimeCreated": ,
    "TimeUpdated": ,
    "Workheads": [{
            "ID": "",
            "Name": "",
            "Code": ""
        },
        {
            "ID": "",
            "Name": "",
            "Code": ""
        }
    ]
},
...
]

This JSON is being fetched into my angular app through an Observable from an HTTP get() request.

I am looking for help in filtering the workhead.Code section in order to obtain specific JSON objects within the array by matching the inner workhead.Code with a user-provided string (for example, workhead.Code == 'CS2230').

Your assistance would be greatly appreciated.

Answer №1

Your request for data retrieval is somewhat unclear. Assuming you require the complete objects rather than just the inner "Workheads", you can utilize the filter() method to achieve this:

const data = [{
  "ID": "",
  "UEN": "",
  "Name": "",
  "Address": "",
  "Telephone": "",
  "Fax": "",
  "Email": "",
  "Website": "",
  "Postal": "",
  "Status": "",
  "TimeCreated": "",
  "TimeUpdated": "",
  "Workheads": [{
    "ID": "",
    "Name": "",
    "Code": "abc"
  }, {
    "ID": "",
    "Name": "",
    "Code": "def"
  }]
}];

// Retrieve an array of objects containing a specific code.
const getRelatedByCode = (arr, userProvidedCode) => {
  return arr.filter((i) => {
    return (i.Workheads || [])
      .some(wh => wh.Code === userProvidedCode);
  });
}

console.log(getRelatedByCode(data, 'abc')); // Returns array with the object
console.log(getRelatedByCode(data, 'zzz')); // Returns empty array

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

JavaScript issue with confirm/redirect feature not functioning as expected

A demonstration of JavaScript is utilized for deleting an employee in this scenario... <script type="text/javascript"> function deleteEmployee(employee) { var confirmation = confirm('Are you sure?'); if(confirmation) { ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

Successive vows

I'm trying to retrieve responses from four promises, but I currently have to call each function in sequence one after the other. In my code, you can see that I trigger the next function within the promise callback of the previously called function. H ...

Initializing Three.js to load the model

I have a 3D model that I initially had in the 3DS format. I then converted it to OBJ and finally to JS format. Now, my goal is to load this model into another JS file. Below you'll find the code snippet I've written for this purpose: var loader ...

Unstyled Cards Failing to Receive Design

I am currently working on creating a prototype that utilizes two Bootstrap 4 cards to display information from a form and store related information from another form in the second card. The current layout of this setup can be observed below: This JSFiddle ...

Can a callout or indicator be created when a table breaks across columns or pages?

As we develop HTML pages for printing purposes, one specific requirement for tables is to include an indicator like "Continues..." below the table whenever a page or column break occurs. Additionally, in the header of the continuation of the table, we need ...

Error encountered: Exceeded maximum update depth in Material UI Data Grid

Encountering an error or warning when inputting rows in the table that is causing the screen to freeze. Warning: Maximum update depth exceeded. This issue can arise when a component triggers setState within useEffect, but useEffect doesn't have a de ...

React: Oops! Looks like there's an issue - this.props.update is not defined as

Hello everyone, I'm diving into the world of programming for the first time and I might ask some silly questions along the way. Currently, I'm working on integrating a date picker into a search application built with React. The user should be ab ...

How can I defer Tween.js animation in three.js until a button is specifically clicked?

I am trying to implement a tween animation for my camera in three.js that should only start when a specific object is clicked. This object can be within the scene or it could be a simple HTML button. The code snippet below demonstrates how the camera anima ...

Waiting for the code to execute once the filtering process is completed in Next.js using Javascript

I'm seeking a way to ensure that my code waits for the completion of my filter function before proceeding. The issue arises because my filter function, which incorporates another function called useLocalCompare, causes a delay in execution. This delay ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

What is the process for incorporating Material-UI into a JSFiddle project?

I'm having trouble figuring out how to load and use the Material UI script on platforms like JSFiddle or SO's code editor, even though I can add it with NPM. Check out this JSFiddle example <script src="https://unpkg.com/@material-ui/core/um ...

When utilizing document.addEventListener in JavaScript, Firefox fails to report exceptions triggered by DOMContentLoaded

I'm developing an internal framework that must be independent of any external dependencies such as jQuery. I'm working on implementing a custom DOM ready-style functionality, where callbacks in the ready queue should continue executing even if an ...

Creating a hierarchical tree visualization with React JS using JSON data

As a newcomer to React JS, I've been working on a project for the past three days and need some help. My task is to create a category list structured like this: Category1 ->Sub-Category1 ->Sub-Category2 Category2 Category3 . . . CategoryN I h ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

Once the GeoJson data is loaded with map.data.loadGeoJson, the circle events are obscured by the polygons from the

When I use map.data.loadGeoJson() to load a Geo Json file, the markers and circles on my map are being covered by polygons and their events cannot be clicked. Below are some sample codes for reference. How can this issue be resolved? Is there another way ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

My code fails to recognize the top property when the window size is 1300px

Error at the Top Not Being Recognized: Hello, I am facing an issue where the top part of the webpage does not behave correctly when the window size is less than 1300px. The condition set for 100% top only applies after refreshing the page; otherwise, it d ...

What steps can be taken to resolve the issue of being unable to rename an element in Typescript?

Why does VS code editor sometimes prevent me from renaming my typescript symbol using the f2 key? I keep encountering the error message "This element cannot be renamed." https://i.stack.imgur.com/mmqu9.png In some of my other projects, I am able to renam ...

Tips for preventing duplicate imports in Sass with the @use rule in Webpack

My sass modules have the ability to import each other as shown in the examples below: // LinearLayout.scss @mixin LinearLayout { ... } linear-layout { @include LinearLayout; } // ScrollView.scss @use "LinearLayout" as *; @mixin ScrollView { ...