Is there a way to dynamically retrieve a JSON element in Typescript?

I am using a data grid throughout my application, and currently, I am retrieving the selected rowid with the following code.

Here is the HTML snippet:

<tbody>
   <tr *ngFor="let ddata of tableData.data; let i = index" (click)="setClickedRow(ddata)" [class.active]="ddata.discountauthorizationid == selectedRow">
      <td *ngFor="let dr of tableData.record | paginate: { itemsPerPage: pageItem, currentPage: p }">{{ddata[dr]}}</td>
   </tr>
</tbody>

In the component.ts file, I handle this as follows:

this.selectedRow = ddata.discountauthorizationid;

console.log("You selected!",ddata.discountauthorizationid);
this.dataService.changeMessage(ddata.discountauthorizationid);

Now, I aim to make this process entirely dynamic by defining the primary id like this:

@Input() primaryid: string

I would like to access data.(some_primaryid) in a way that resembles accessing an array using keys. Can this be achieved? If so, could you provide guidance on how to do it?

Answer №1

Learn how to retrieve the value below.

let myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.primaryId = "userId";
    
    $scope.data = {
       "userId": 1,
       "accountId": 23,
       "testId": 5
    };

  
$scope.changeId = ()=>{
    
   $scope.primaryId = "accountId";
};
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
<div ng-controller="MyCtrl">
   {{primaryId}} is :  {{data[primaryId]}}!
 <button ng-click="changeId()">
  Change ID
 </button>
</div>
</body>
</html>

Answer №2

After numerous attempts, I finally found a solution. The code now reads as follows: ddata[primary_id_var]. Using ddata[{{primary_id_var}}] did not yield the desired outcome.

Answer №3

Latest Information, as per your feedback:

class Info {
    public identifier: string;
}

let key = 'identifier'; // key will be the input provided
let infoData = <Info>{ identifier: '456' };

alert(infoData[key]); // 456

Prior Response: I may not have fully understood your query, but based on your previous statement:

I want to retrieve this data (some_identifier) similar to how we access elements in an array using a key and assign the key with a variable. Is this achievable? If so, how?

Absolutely, it can be done. You can access properties in this manner:

console.log(data['some_identifier']);
data['some_identifier'] = '789';

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

What strategies can I implement to reduce the size of my Angular application to 500K or less?

I have been researching ways to reduce the size of my Angular application, but have not yet found a solution that significantly decreases its size. Currently, my application is 4M in production and 14M in development. So far, I have tried: Lazily loadin ...

When I attempted to POST a js::array in JSON, the response returned "undefined:undefined"

I have a javascript array on the frontend that I need to send to my Tomcat server. Currently, I am using the following code but encountering issues: console.log("preview list. postUsers()"); console.log(Ext.getCmp("preview-container").get ...

Allow users to create an unlimited number of components by simply clicking on Ionic with a customizable click event

Have you ever used the Garmin Connect app to create training sessions? It has a feature where you can easily add repetitions by clicking a button. Each time you click, a new module appears. Check out this example: click In Ionic, I'm wondering how to ...

Optimize performance: sending large arrays of numbers ([Double]) over HTTP using Swift

After countless hours of research and testing, I find myself seeking advice on a perplexing issue: A Brief Overview My current challenge involves transmitting large arrays of Doubles from an application to a server. Naturally, the goal is to compress thi ...

Troubleshooting the error message "Encountering issues with Module build failed (from ./node_modules/postcss-loader/src/index.js)"

Running ng serve results in compilation failure after the chunks are generated. The same codebase is functioning on a co-worker's computer with identical versions as listed below: Node version: 10.16.3 NPM version: 6.9.0 @angular/cli: 7.3.9 Tried ...

The error message "tsc not found after docker image build" appeared on the

My goal is to deploy this program on local host. When I manually run "npm run build-tsc," it works successfully. However, I would like Docker to automatically run this command when building the image. Unfortunately, I receive an error saying that tsc is no ...

Using ngFor to destructure two variables simultaneously

When working with Python, I found a way to unpack both variables in each tuple at every iteration. l = [(1, 2), (4, 5), (8, 9)] for k,v in l: print("k = ", k) print("v = ", v) print("-------") # k = 1 # v ...

Understanding the complexity of defining the type of a function can be challenging. If you're tasked with a complicated function, determining its type

Let's break it down: Dict is defined as { [key: string]: () => any } The desired return value is represented by X I am attempting to create a type for a function that: Takes in a dictionary Dict T Returns an X Now, X also functions as a functio ...

Generating a multidimensional associative array based on user inputs from a form

What is the best way to transform form input data into a multidimensional associative array? This is how the form appears: <div id="items"> <h4>Engraving Text</h4> <div class="item" data-position="1"> <h4 id="en ...

Suggestions for displaying combination data in JSON format?

Currently, I am working on integrating an API that provides information on the number of users using a specific app. For instance, let's say I need to retrieve data indicating 10 individuals are exclusively using App1, 8 are solely using App2, 8 are ...

Retrieving XML Information from a Textual Source

When I upload a file of XML type, it generates an input stream. In order to obtain the XML data in the code behind, I convert the input stream into a string using the following: StreamReader stream = new StreamReader(Request.InputStream); string x = str ...

What methods can I use to gauge the loading time of an AJAX request and showcase a loading panel?

I am facing an issue with my AJAX request that sometimes deals with a large JSON object. I need to display a loading panel during this process, similar to the one shown in the image below (scaled at 45%): https://i.stack.imgur.com/rw9ft.jpg The problem I ...

Table pagination in Mat is experiencing overflow, and the button styles have also been customized for a unique look

I implemented a mat paginator feature, however, I am facing an issue where the alignment of items per page options is not correct. Below is the snippet from component.html file: <div class="table-responsive" *ngIf="resultssummaries"> &l ...

Newest Angular package.json

Each time I attempt to update my Angular components to the latest version, I encounter the same error. It seems like a never-ending cycle... npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/ ...

Using TypeScript to Declare Third Party Modules in Quasar

I'm currently trying to integrate Dropzone-vue into my Quasar project. However, I've encountered an issue as I can't directly install and declare it in a main.js file due to the lack of one in Quasar's structure. Additionally, an error ...

Angular first renders a component before removing another one using ng-If

I have two components that are displayed one at a time using an ngif directive. <app-root> <first-Comp *ngIf="showFirst"></first-Comp> <second-Comp *ngIf="!showFirst"></second-Comp> </app-root> Here are some key ...

What is the best way to transfer user data from the backend to the frontend?

I successfully created a replica of YelpCamp using Node and EJS, but now I am attempting to convert it into a Node-React project. Everything was going smoothly until I encountered an issue while trying to list a specific user in the SHOW route. In order to ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

Updates made in the type declaration files are not being displayed

I'm currently working on an express app and I have been trying to add a new property to the Request's class instance. To achieve this, I created a type.d.ts file at the root of my project that looks like this: type User = { name: string } de ...