Changing dot notation to bracket notation in Angular

Having trouble using dynamic columns in a Primeng table? The column fields need to be in bracket notation for this setup. What if you have a column with nested JSON structure and you're not sure how to write that in bracket notation? Don't worry, we can help you out. Check out the example below:

Your JSON data:

[
    {
        "studentName": "test",
        "email": null,
        "phnNumber": 1,
        "subjects": [
            {
                "subjectName": "Maths",
                "subjectTeacher": "Elon"
            },
            {
                "subjectName": "English",
                "subjectTeacher": "Shakespeare"
            }
        ]
    },
    {
        "studentName": "test2",
        "email": null,
        "phnNumber": 1,
        "subjects": [
            {
                "subjectName": "CS",
                "subjectTeacher": "Elon"
            },
            {
                "subjectName": "English",
                "subjectTeacher": "Shakespeare"
            }
        ]
    }
]

Your typescript code:

this.cols = [
      { field: 'studentName', header: 'Student Name' },
      { field: 'email', header: 'Email' },
      { field: 'phnNumber', header: 'Contact No' },
      { field: '["subjects"][0]["subjectName"]', header: 'Subject Name' }

    ];

Your template code:

<ng-template pTemplate="body" let-student let-columns="columns">
    
        <td *ngFor="let col of columns">
            {{student[col.field]}}
        </td>

</ng-template>

If you were wondering about accessing the 1st subject of student 1 in dot notation (students[0].subjects[0].subjectname), and want to replicate it in bracket notation, feel free to ask!

Answer №1

Consider trying it this way:

students[i]['subjects'][j]['subjectName']

To access the first subject of the first student:

students[0]['subjects'][0]['subjectName']

Example : https://stackblitz.com/edit/angular-nt1yt5

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

Accessing file uploads in Angular 2

<div class="fileUpload btn btn-primary"> <span>Select File</span> <input id="uploadBtn" type="file" class="upload" value="No File Chosen" #uploadBtn/> </div> <input id="uploadFile" placeholder="No File Selected" disable ...

What is the method for deducing the return type based on the parameter type in a generic function?

Check out this code snippet featuring conditional types: class X { public x: number; } class Y { public y: number; } type DataCategory = "x" | "y"; type TData<T extends DataCategory> = T extends "x" ? X : T extends "y" ? Y : ne ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

Using a jQuery plugin within an Angular 2 component: A step-by-step guide

Looking to implement an image slider plugin called Vegas only on the home page within my Angular 2 application. The Vegas jQuery plugin has been added via npm and is located under the /node_module directory. The following code snippet shows my home page c ...

Next.js does not recognize the _app file

After including the _app.tsx file in my project to enclose it within a next-auth SessionProvider, I noticed that my project is not recognizing the _app.tsx file. Even after adding a div with an orange background in the _app.tsx file, it does not reflect in ...

Acessing files from Azure Blob within the Aurelia UI: Download or View now!

I currently have my files stored in Azure and I am looking for a way to either download or view them on the client side. This is how I envision the process: Azure -> Api -> Client UI (Aurelia) While I have come across several C# examples, I am unsure of ...

What is the equivalent of html script tags in Webpack 2?

I recently downloaded a new npm module that suggests including the following code in my project: <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" /> <script src="node_modules/ng2-toastr/bundles/ng2-toastr.min.js"&g ...

Using RxJs in Angular, you can invoke an observable from within an error callback

I have a scenario where two observable calls are dependent on each other. Everything works fine, but when an error occurs in the response, I need to trigger another observable to rollback the transaction. Below is my code: return this.myService.createOrde ...

Issue: Module 'stylelint' not found in Angular Project

I've been attempting to execute this command to validate all of the .scss files (and even tried with .css files) and I keep encountering this error. $ stylelint "apps/**/*.scss" It worked once before but not anymore, even after restarting my compute ...

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

Angular 6 form input value displays incorrectly after dynamically closing a tab

After adding a child-component with a form inside a tab, I noticed that when I closed the tab, the child-component form value was changed to the deleted tab. However, the span value remained correct. It's quite strange - could this be a bug? Check ou ...

The ng-model used within an *ngFor loop is not displaying the correct value

I am working with a JSON file in my Angular2 App. The specific JSON object I am referring to is named tempPromotion and I am trying to access the data within ['results'] like this: tempPromotion['response_payload']['ruleset_list ...

Looking to update the URL from another component?

My current project is using Angular 6 and I am working on creating a list of buttons on the left panel such as "Ice cream", "Pop corns", and more. The goal is for users to click on these buttons which will then change the URL of the add button located in t ...

Merge a pair of values into an object using a JOLT conversion

I am new to using Jolt and I have a source format that was generated from some software but it lacks good structure. I want to transform it so that each piece of text ("First text" and "Second text") is associated with a link ("First text -> Link of first ...

Strengthening the security of PHP using JSON

I'm working on a PHP script that receives data from an Android application. What security measures should I implement to ensure the safety of this script? Are functions like isset enough? <?php require ('config.php'); $connection=mysqli ...

Developing a Swift-based application for blogging

Currently in the process of developing a blog application for a website, I'm intrigued by the various approaches that others are taking. An essential aspect of this project involves working with JSON data containing specific fields such as Title, Date ...

Is there a way to retrieve Chinese Romanization using the JSON format from the Google API?

I’m trying to find a solution for translating English to Chinese and, so far, I’ve managed to make that work. However, I now face the challenge of obtaining Chinese Romanization as well. To clarify, I want "God" to translate to both 神 and Shén; un ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

Using Python to loop through and make changes to JSON elements

I am facing a challenge with the following data structure in JSON format: { "taskDefinition": { "containerDefinitions": [ { "memoryReservation": 1040, "mountPoints": [ ], "name": "staging-web1", "image" ...