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

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

I attempted to retrieve the id field of a jsonwebtoken following the user's login, but unfortunately, I was unable to access it

While working on the backend of my application, I encountered an issue trying to save the id field from a JSON Web Token (JWT) to an item that I created after a user logs in. Although I am able to log the JWT information successfully, I'm facing diffi ...

Send a POST request with an NSDictionary set in the HTTPBody

I need to make a web service call using the POST method. I have to send a dictionary along with a URL to my web service. Below are the parameters required for my web service: ConversationMessage { authorUserId (string, optional), subject (st ...

Example of Using Bluebird in a Chain of Catch and Then Functions

I am struggling to understand how promises work in my code flow setup. I want to create a register function with multiple steps, but I'm unsure of what is achievable and what is not. Imagine I have a register function where I need to: register a u ...

Angular 2 - Beginner's guide to updating the header when navigating to a new route or page

SOLVED I am faced with a challenge involving multiple components in Angular2. Specifically, I have the following components: home component, default header, detail component, and detail header component. Each header has a unique layout. At the Home pa ...

Steps to avoid reinitializing the component upon changing routes in an Angular 9 component

In my component, the width of a chart is stored in a variable (because I can't use style for d3). However, every time the route changes, all variables in this class component become undefined. I have tried using ngIf, services (which also become unde ...

Mapping fields in Angular collectively

I'm currently working on implementing a modal, and I'm looking to link values from the formBuilder to a specific property. Here's the snippet of code I'm working with: submit(data?: any) { // THE FOLLOWING CODE WORKS, BUT IT'S ...

Ways to Access HTTP Request Headers in Angular 6 upon Page Load

Is it possible to retrieve request header information in Angular 6/7 upon application initialization? I specifically require access to header values for security and access management purposes, as these values are set in the headers during the usage of th ...

Is it better to use a single struct or multiple structs for handling nested JSON

When working with nested JSON in Go, I often find myself wondering about the most correct or idiomatic way to create the struct it's parsed into. Single struct: type myStruct struct { Fields struct { Struct0 struct { Field0 s ...

Guide to building an Angular circular progress indicator using Scalable Vector Graphics (SVG)

I have designed an angular circular progress bar, but I am facing an issue with making the percentage value dynamic. I have managed to retrieve the dynamic value from an API, but I am unsure of how to implement it in creating a circular progress bar using ...

Angular project set up with dynamic polyfill inclusion based on .browserslistrc configuration

In order to ensure that our software is compatible with older browser versions, we need to implement polyfills for Angular since it does not do this automatically. To achieve this, I am looking to add custom webpack configuration. Currently, I am working ...

What are the steps to create a JSON file structured in a tree format?

Can you provide instructions on creating a JSON file in the following tree format? root child1 child11 child2 child21 child22 child3 child31 I am looking to generate a sample JSON file that adheres to the ...

Typescript patterns for creating a modular library design

Transitioning a JavaScript project to TypeScript has been challenging for me, especially when it comes to establishing a solid design pattern for the library's modularity. Main Concept The core functionality of my library is minimal. For instance, i ...

Utilizing Vue and Typescript for efficient dependency injection

After attempting to use vue-injector, I encountered an issue as it was not compatible with my version of Vue (2.6.10) and Typescript (3.4.5). Exploring other alternatives, there seem to be limited options available. Within the realm of pure typescript, t ...

Look for and choose various fields from a lengthy JSON object

I am working with a JSON object that contains a large list of offerValue objects. { "Code": 0, "response": "SUCCESS", "offerValue": [ { "id": "111", "name": "ABC", "flag": "V" }, { ...

Send an encrypted POST request containing a JSON body to the R server

Currently, I'm working on utilizing R to send an encrypted request to an API. The specific request in question is the /v3/orders/ one. This request necessitates the utilization of an API key and secret, along with a progressively increasing nonce. ...

Creating a new object in a Redux selector and returning it can be achieved by following these steps

Is there a way to create a new object in Redux selector and return it? I've been searching online, but haven't found an answer. For example: export interface UserModel { user: string, job: string, contact: string, sex: string // ...

What is the solution to the tkinter TypeError: keys must be str, int, float, bool or None, not Button error?

import json from tkinter import * import os listai = json.load(open("listai.txt")) listap = json.load(open("listap.txt")) dict = {} def dictAdd(item, value): global listai, listap print(item) #i did this so i could see where it was getting t ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...