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

The jQuery toggleClass() function is not being applied successfully to content that is dynamically generated from

I've created an awesome collection of CSS-generated cards containing icons and text with a cool animation that expands upon tapping to reveal more icons and options. I carefully crafted the list to look and behave exactly how I wanted it to. But now, ...

Do I need to convert AngularJS to .ts for an Angular/AngularJS hybrid application?

Currently in the process of upgrading from AngularJS v1.25 to Angular 14 using the ng-Upgrade approach outlined on angular.io/guide/upgrade. Adding an extra challenge, our main page is built with ASP.NET MVC 5, and I am aiming to incorporate the Angular CL ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Challenge with having both Double and Boolean attributes in JSON structure

I want to express my gratitude to all those who are taking the time to read my post. I am currently dealing with a JSON response that includes objects with different data types in the same list. Specifically, one object has a Double data type attribute whi ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

Incorporating a visual progress indicator on the webpage

I am attempting to create a progress bar in Angular using the angular mat-stepper. Here is the code I have written so far: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { Ap ...

The object of type 'AttrList' cannot be serialized as JSON

class SearchSuggest(View): def get(self, request): key_words = request.GET.get('s','') re_datas = [] if key_words: s = JobType.search() s = s.suggest('my_suggest', key_words, completion={ ...

Tips for populating array values in an Angular9 template using forms

.html page <pre> <div *ngFor="let data of data;let i=index" class="row_wrap"> <div class="row_inner_wrap"> <div class="row"> <div class="col-md-12"> <div class="col-md- ...

PHP cannot access JSON encoded data retrieved from Codeigniter through AJAX

I am currently working on implementing a live search feature in a CodeIgniter file using AJAX autocomplete. $(this).ready( function() { $("#id").autocomplete ({ minLength: 1, source: function(req, a ...

Change an ISO date format to DD:MM:YYYY HH:MM using Angular

I currently have my date in this format: 2022-11-21T21:07:56.830-07:00 However, I am looking to convert it to the following format: 21/11/2022 07:56 ...

Tips for extracting parameters from a JSON String using JavaScript

When attempting to parse a JSON String, I am encountering an issue where the parsed value is coming up as undefined. You can view the code on this jsfiddle link. <input type="submit" onclick=testJSON() value="Test"/> <div i ...

Which rxjs operator should be used when dealing with nested subscriptions in the presence of an if statement?

In my Angular/Typescript project, I am dealing with 2 subscriptions. Each subscription is subscribing to its own observable A and B, which are located outside the component in the service file. Sometimes, when A changes, B may or may not change based on c ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...

What is the process for declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

Retrieve information from the app-root and transfer it to the component

<body> <app-root data="myData"></app-root> </body> I have added the myData at index.html and now I want to retrieve it to use in a component. What is the best way to access this data? Thank you. ...

Setting the selected <ion-option> in Ionic 3

Is it possible to programmatically set a default selected option in a dynamically created select menu using Ionic 3 and Angular? I want to make sure "Select State" is automatically chosen if the user hasn't made a selection yet, but I'm having t ...

Customizing hover color with tailwind CSS

How can I change the color of an icon on mouseover using Tailwind CSS? I have tried to go from this https://i.sstatic.net/ObW6C.png to this https://i.sstatic.net/Tagp3.png, but it's not working. .btn { @apply agt-h-10 agt-w-10 agt-bg-zinc-100 agt- ...

Deciphering complex JSON structures using Google Scripts

Struggling to find a solution online for successfully parsing JSON output from an API request. Focusing on extracting data from the "ResultData" section of this API JSON Example Output: {"url":"","id":69,"user":3,"inputdata":{"Q1":"Response1","Q2":"Respo ...

The functionality of 'ngbPopover' in Ng-bootstrap may be affected if the parent container contains a 'transform' css property

Struggling to implement Ng-bootstrap's 'ngbPopover' functionality, I encountered a frustrating issue where the popover would not display after clicking the button. After numerous hours of troubleshooting, I was relieved to discover the root ...