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

Storing Angular header values in local storage

saveStudentDetails(values) { const studentData = {}; studentData['id'] = values.id; studentData['password'] = values.password; this.crudService.loginstudent(studentData).subscribe(result => { // Here should be the val ...

An efficient method for extracting data from a JSON array and integrating it into a DataTables display

I am struggling to populate data tables with values from a PHP file that returns JSON responses. Despite receiving the JSON response, I am unable to successfully append the data to the data table. Below is the code snippet used for generating the JSON resp ...

Navigating from a Card to a new View in Angular

I am currently developing a project using Angular (latest version). Within my application, I have the functionality to dynamically generate bootstrap cards from an Order Array and display them in my "Order-Item-Component through its respective template. ...

detect faces in an image using Microsoft's cognitive services by uploading an image from your device

As a newcomer to Face Recognition technology, I have been searching for answers to my questions without much success. I have learned that uploading an image from the web requires using Content-Type application/json and providing the image URL in the JSON ...

typescript create object with immutable property already set

Can you create an object literal in JavaScript and define its interface with read-only properties simultaneously? For instance let obj = { readonly prop1: 'hello', readonly prop2: 'world' } ...

How to effectively handle null values using try..catch statement in typescript

As a beginner, I am learning how to write a try/catch statement in TypeScript. My issue is that there is a function within the "try" block that returns null. How can I implement code in the "catch" block specifically for when the function in "try" returns ...

Encountering a 'Exception Unhandled' error in C# when attempting to parse JSON data

I am currently working on extracting data from a JSON file and updating the text of a label in C#. However, I have encountered an 'Exception Unhandled' error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The best overloaded method ...

I am looking to display a single column in a SQL query as a JSON array containing all the child values

My query involves retrieving various fields from a product table and also assigning multiple tags to each product using a ProductTagMapping table. I want to include a Tags column in my output that contains a JSON Array of the associated Tag Names from a Pr ...

Creating dynamic dropdown menus using JSON files in jQuery mobile is a useful technique for enhancing user experience on

I am working with a massive table (8 MBytes) that I need to filter using a small JavaScript application. The process works as follows: Countries Regions Skills I want the user to select one country, one region, and multiple skills as filters. Based on ...

Tips for resolving the issue: Uncaught (in promise) SyntaxError: Unexpected end of input in Fetch API

When I click the button, I am executing this function. Despite adding a header in my API, an error is still being displayed. Here is the code snippet for the function: let getData = () => { console.log("getData function started"); ...

Looking for dates within JSON data using Python

Seeking advice on efficiently searching through JSON data to find today's date/time and retrieve the corresponding value. Here is a snippet of the JSON data structure: [ { "startDateTime": "2018-04-11T14:17:00-05:00", "endDateTim ...

An array in JSON format containing only one element

I am currently working on a project that involves JSON format output. I am in need of some clarity regarding the structure of JSON arrays. Specifically, I'm curious about how to handle fields that allow multiple entries in an array format. In cases wh ...

React Routing: Unleashing the Power of Multi-Level Routing

In my quest to create a route with multiple levels (<Route path="/hello/world" element={<a>hello world</a>} />), I encountered a few issues. Here are the versions I am using: react: 18.1 react-router-dom: 6.3.0 Success with O ...

Utilizing the power of KendoUI and Angular2 for autocomplete: governing accepted values

I successfully integrated the KendoUI Autocomplete feature with live search functionality. It is working well and meeting my expectations. However, I want to limit the autocomplete suggestions to values from the list only. For example, if I type "London" ...

Incorporating fresh JSON information into an established database

I'm currently facing an issue with adding new data (from JSON) to an existing table using jQuery. Within my HTML, there's a sample table structure like this: <table data-role="table" data-mode="columntoggle" class="ui-responsive" data-column ...

Exploring JSON data and making precise adjustments in JavaScript

I am attempting to create my own database using JavaScript and JSON, but I have encountered some issues along the way. My main struggle is figuring out how to extract specific content from a JSON file. After doing some research, I came across this code sn ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Improving the management of user input in Lit components

I am seeking a more efficient method to manage all inputs within my lit component while minimizing the code usage. I am also employing Typescript in this process, utilizing @change=${this.handleInput} for all input fields. Below is an example of how the ha ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...

The concealed [hidden] attribute in Angular2 triggers the display of the element after a brief delay

I am currently utilizing the [hidden] attribute within my application to conceal certain elements based on a specific condition. The situation is such that I have two divs - one for displaying results and another for showing the text "No results". Both t ...