Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript?

0- {
  EmpId: 101,
  EmpName:'abc'
  Role :
     0- {roleid :1, 
         role:Admin, 
         isdeletee:true},

     1- {roleid :2,
         role:user, 
         isdeletee:true},

     2- {roleid :3, role :Admin, 
        isdeletee:true}

}
1- {
  EmpId: 102,
  EmpName:'xyz'
  Role :
     0- {roleid :1, 
         role:Admin, 
         isdeletee:true},

     1- {roleid :2,
         role:user, 
         isdeletee:true},

     2- {roleid :3, role :Admin, 
        isdeletee:true}

}
2- {
 EmpId: 103,
 EmpName:'xez'
 Role :
     0- {roleid :21, 
         role:userx, 
         isdeletee:true},

     1- {roleid :2,
         role:user, 
         isdeletee:true},

     2- {roleid :31, role :ad, 
        isdeletee:true}

},

Answer №1

It can be challenging to decipher the exact specifications you are seeking based on your inquiry. Do you require something akin to this? The following code snippet serves as an illustrative example, and in practical application, null checks would typically be incorporated.

const response = [{
    EmpId: 101,
    EmpName: "abc",
    Role: [{
        roleid: 1,
        role: "Admin",
        isdeletee: true
      },
      {
        roleid: 2,
        role: "user",
        isdeletee: true
      },
      {
        roleid: 3,
        role: "Admin",
        isdeletee: true
      },
    ],
  },
  {
    EmpId: 102,
    EmpName: "xyz",
    Role: [{
        roleid: 1,
        role: "Admin",
        isdeletee: true
      },
      {
        roleid: 2,
        role: "user",
        isdeletee: true
      },
      {
        roleid: 3,
        role: "Admin",
        isdeletee: true
      },
    ],
  },
  {
    EmpId: 103,
    EmpName: "xez",
    Role: [{
        roleid: 21,
        role: "userx",
        isdeletee: true
      },
      {
        roleid: 2,
        role: "user",
        isdeletee: true
      },
      {
        roleid: 31,
        role: "ad",
        isdeletee: true
      },
    ],
  },
];

const role = response
  .filter((emp) => emp.EmpId === 102)[0]
  .Role
  .filter((roles) => roles.roleid === 2)[0]
  .role;

console.log(role);

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

Angular: Update form control validation when another form control changes

If you want to view the project in a stackblitz, please click here. In the project, there is a reactive form with controls named firstNumber, secondNumber, and thirdNumber. The validation requirement for the form control thirdNumber is that its value shou ...

Steps for retrieving JSON data from REST API on on-premise TFS

We are utilizing on-premise TFS Version 15.105.25910.0, also known as TFS 2017, to retrieve JSON data (specifically for a given Work Item id) using Postman for sending/receiving requests. Initially encountered permission denied errors which were resolved ...

Angular Tutorial: Understanding the Difference Between TypeScript's Colon and Equal To

I've been diving into the Angular4 tutorial examples to learn more about it. https://angular.io/docs/ts/latest/tutorial/toh-pt1.html One of the code snippets from the tutorial is as follows: import { Component } from '@angular/core'; @Co ...

Issue when utilizing TypeScript MongoDB Definitions (Unable to locate namespace)

I am currently working on implementing MongoDB typings that I installed using the following command: npm install @types/mongodb -D Now, I want to utilize these types within a function like this: export default async function insertOne(collection:any, da ...

Dynamic data in highcharts pie charts allows for the customization and selection of colors

I am working with a pie chart that looks like this { type : 'pie', data : [], //dynamic data goes here center : [50, 15 ], size : 80, showInLegend : false, dataLabels : enabled: true, } Now, I am interested in changing the color of ...

Combining actions in a chain within an NgRx effect for Angular

After successfully working on an effect, I now face the challenge of chaining it with a service called in a subsequent action after updating the state in the initial action through a reducer. Here is the effect code: @Effect() uploadSpecChange$: Observab ...

Angular implementation of reverse geocoding

retrieveAddress(lat: number, lng: number) { console.log('Locating Address'); if (navigator.geolocation) { let geocoder = new google.maps.Geocoder(); let latlng = new google.maps.LatLng(lat, lng); let request = { LatLng: latlng }; ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

Managing and parsing intricate nested JSON structures in Python

Currently using Python to navigate through each key-value pair in a dictionary. I successfully navigated through key-value pairs where the value is another dictionary, but am facing a challenge when trying to handle lists within that inner dictionary. Belo ...

Interactive table created with DataTables that automatically updates the dynamic JSON data source whenever changes are made to the table

Using the Datatables plugin, I am dynamically populating a table with HTML rendered from a JSON array. However, I need the table to update the model (datasource) stored client-side whenever an edit is made. When navigating to a new page on the table, it s ...

Every time I execute my program, it consistently displays a 500 error message when using both the POST and GET

I'm seeking assistance with mvvm as I am new to it. Can anyone help me in displaying details based on the selected date? Upon running my code, I encounter a 500 error with both the post and get methods. Schedule.cshtml <div class="col-lg-8" ng-ap ...

Implementing a boolean toggle method in Typescript for a class property

Hello there, fellow programmers! I am interested in changing the value of a class field using a method. I have a button in Angular that, when clicked, triggers the onSave() method: export class CourseComponent { isActive:boolean; onSave() { ...

The react decorator for maintaining type safety fails to identify the appropriate ReturnType of the supplied function

I want to enhance the redux connect feature by using it as a decorator for a specific reducer/state. Although I know that redux connect can already be used as a decorator, I am curious about why my custom implementation does not work the way I expect. Her ...

Recursively map elements of a TypeScript array to keys of an object

I am looking to create a structured way to specify paths for accessing objects, ensuring that the path is correctly typed based on the object type. Let me illustrate with an example. Consider the following data: const obj = { name: 'Test', ...

Navigate through each file or image within a directory using Angular

I am facing a challenge with my app where each product has a gallery containing a random number of images, each with a completely unique name. These images are located in /src/assets/images/products/:id/. Currently, I am struggling to loop through and add ...

Guide to establishing a connection to CloudantDB through spark-scala and extracting JSON documents as a dataframe

I have been attempting to establish a connection with Cloudant using Spark and read the JSON documents as a dataframe. However, I am encountering difficulties in setting up the connection. I've tested the code below but it seems like the connection p ...

Ways to address the Generic Object Injection Sink eslint error (security/detect-object-injection)

I am seeking a solution to resolve this issue without needing to deactivate eslint. Moreover, I am eager to comprehend the cause of the error. const getMappedCard = (cardName: CardName) => { const mappedCards = { Mastercard: <Mastercard /> ...

When using string as a primitive type in Vue 3, what distinguishes the usage of PropType in props from not using it?

The documentation explains how Vue does runtime validation on props with defined types. To enable TypeScript to recognize these types, constructors are cast with PropType. The code example in the documentation uses success: { type: String }, whereas it c ...

Tips for resetting and enabling file uploads with ng2-file-upload

My file upload functionality is working smoothly using ng2-file-upload. However, I am facing a challenge in handling server-side errors and resetting the file uploader. How can I achieve this? Below are the snippets of code that I am currently using: HTML ...

TypeORM: establishing many-to-one relationships between different types of entities

Trying to represent a complex relationship in TypeORM: [ItemContainer]-(0..1)---(0..n)-[ContainableItem]-(0..n)---(0..1)-[ItemLocation] In simpler terms: A ContainableItem can exist either within an ItemContainer or at an ItemLocation. Although it cannot ...