What is the best way to retrieve a value from an array?

Using ASP.net Core, I receive information from my API. In Angular, the data looks like this:

0: {Id: 3, Role_Name: 'ITAdmin'}
1: {Id: 4, Role_Name: 'Admin'}
2: {Id: 5, Role_Name: 'user'}

I want to extract values from this array for my Current User. Something similar to storing them in an array or another method.

var rolename = ITAdmin, Admin, User 
var id = 3, 4, 5

To display the role name and its corresponding ID separately.

Thank you for your assistance :)

Answer №1

If you want to extract ids and rules from an array, you can utilize the reduce method as shown below:

// initial array
const sourceArray = [{
    Id: 3,
    Role_Name: 'ITAdmin'
  }, {
    Id: 4,
    Role_Name: 'Admin'
  }, {
    Id: 5,
    Role_Name: 'user'
  },
];

// default empty target object
const defaultList = {
  ids: [],
  roles: [],
};

// processing the source array using reduce function
const reducedObject = sourceArray.reduce((obj, item) => {
  // extracting id and role from each array item
  const {Id, Role_Name} = item;
  
  // updating the list
  return {
    ids: [...obj.ids, Id],
    roles: [...obj.roles, Role_Name]
  };
}, defaultList);

// extracting ids and roles from the reduced object
const {ids, roles} = reducedObject;

console.log('ids: ', ids);
console.log('roles: ', roles);

Alternatively, you can achieve the same result in a simpler way using the map function:

// initial array
const sourceArray = [{
    Id: 3,
    Role_Name: 'ITAdmin'
  }, {
    Id: 4,
    Role_Name: 'Admin'
  }, {
    Id: 5,
    Role_Name: 'user'
  },
];

// default empty target arrays for ids and roles
const ids = [];
const roles = [];

// processing the source array using map function
sourceArray.map(item => {
  // extracting id and role from each array item
  const {Id, Role_Name} = item;
  
  // updating the lists
  ids.push(Id);
  roles.push(Role_Name);
});

console.log('ids: ', ids);
console.log('roles: ', roles);

Answer №2

Discover a new code snippet that will output 2 arrays

let id = []
let role = []
const input = [{
    Id: 3,
    Role_Name: 'Manager'
}, {
    Id: 4,
    Role_Name: 'Supervisor'
}, {
    Id: 5,
    Role_Name: 'Associate'
}, ];

for (let index = 0; index < input.length; index++) {
    id[index] = input[index].Id;
    role[index] = input[index].Role_Name
}
console.log(id)
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

Dynamically generating PWA manifests in Angular 7

I just finished building a Progressive Web App (PWA) using Angular 6. Now, I am looking to customize the icons and start URLs dynamically because the app will be accessed through different URLs, each with its own unique logo assigned to it. Is there a way ...

Issues with ngClass in AngularAngular's ngClass feature is failing

In my ngClass condition, it looks like this: <div [ngClass]="{'alert alert-danger': alert.type == 0,'alert alert-success': alert.type == 1}" When alert.type == 1, the class is set to alert alert-success. But when alert.type = 0, th ...

Using Bazel, Angular, and SocketIO Version 3 seems to be triggering an error: Uncaught TypeError - XMLHttpRequest is not recognized

Looking to integrate socket.io-client (v3) into my Angular project using Bazel for building and running. Encountering an error in the browser console with the ts_devserver: ERROR Error: Uncaught (in promise): TypeError: XMLHttpRequest is not a constructor ...

Communication between components through a shared service

Imagine you find yourself in one component and need to trigger a method from another component. There are multiple ways to achieve this, which are explained in more detail on this page. Here, I will demonstrate the simplest possible example of how to make ...

Utilize nested JSON Response as row data for ag-Grid in Angular 4

Just starting out with angular and working on a project where I need to display JSON data in a grid. I've opted for ag-grid. Here's the sample JSON response I'm receiving from a rest API: [ { "id": 64, "name": "Utopia", "language": ...

Using TypeScript, effortlessly retrieve objects within React components based on their keys

I am looking for a way to dynamically choose a React component based on a key within an object import React, {useState, useEffect} from 'react' import ComponentA from '@components/ComponentA'; import ComponentB from '@components/Co ...

Typescript: Retrieve an interface containing properties that are found in interface A, but not in interface B

I am currently developing a mapper that will facilitate the translation between a serialized entity state and a form state. In the context of two given interfaces A and B, I am exploring ways to derive a third interface C that includes properties present ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Get the name of the array using JavaScript

Here is an example of my situation: var list1 = ['apple', 'banana', 'orange']; var list2 = ['carrot', 'lettuce', 'tomato']; When I use: alert(list1) I get: apple, banana, orange. This is corre ...

transferring information between two sibling elements in Angular 7

My goal is to display the username of the logged-in user on the home page. I have a LoginComponent, HomeComponent, and I am using a service called DataService.ts for data transfer. The data seems to be reaching DataService.ts but it's not getting to t ...

The whereabouts of the node_modules folder during the development phase

As I dive into Angular 2 app development, I encountered an issue. Installing node modules in each project folder using npm install seems to be taking up a lot of disk space and causing duplication across multiple projects. This led me to consider creating ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

Display the specified [object][object] in the header of Angular PrimeNG Multiselect component

When using angular primeng multiselect, it sometimes displays [object][object] in the header instead of the optional label when in edit/on focus state. Here is my code snippet <p-multiSelect(onFocus)="insertOptions(row,itemProperty.options,itemPropert ...

Is accessing out-of-bounds in Python secure? Is it considered poor practice?

> [1, 2, 3][1:int(1e9)] [2, 3] As someone with a background in C, the code above initially caused me some concern. However, it appears to function as intended. Can this code be relied upon to work consistently in all instances of python3? Is it as effi ...

Understanding how to monitor a Boolean value that fluctuates in real-time within a three.js

Currently, I am working on developing a 3D 4x4x4 tic tac toe game using three.js. In order to determine the win condition for combinations, I have created a boolean array. With a total of 64 blocks (16*4), I have initialized a boolean array of size 64 with ...

What is the method for retrieving data from a node in Firebase Realtime Database using TypeScript cloud functions, without relying on the onCreate trigger?

Being a beginner with Firebase and TypeScript, I have been struggling to retrieve values from a reference other than the triggered value. Despite finding answers in JavaScript, I am working on writing functions using TypeScript for real-time database for A ...

Getting an array of objects following multiple ajax requests

When working on a project, I integrated checkbox filters using ajax. Within my controller, there is an action set up like this: def casinos_filters providers_from_categories = Provider.joins(:categories).where('categories.id = ?', params[:ca ...

What is the best way to fully reload an Angular component when the route is changed?

I'm looking for a way to reload or refresh a sidebar component when the route changes. Below is the code I currently have: constructor( private auth: AuthService, private router: Router, private changeDetector: ChangeDetectorRef ) { ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...

Creating a JSON file from a custom key-value class in Typescript: A comprehensive guide

I am struggling to find an npm package or create my own function that can generate a JSON file from elements within this specific class: export class TranslatedFileElement { private key: string private hasChild: boolean priva ...