ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, 
    AfterViewInit {
       page: Page = new Page({sort: {field: 'description', dir: 'asc'}});
       dataSource: ProvinciaDataSource;
       columns = ['codprovince', 'codprovinciasc', 'description', 'country.codcountry','country.description'];
       labelColumns = {
          'codprovince': {'label': 'Code', 'width': '60', 'align': '', 'format': ''},
          'codprovinciasc': {'label': 'INEC Code', 'width': '60', 'align': '', 'format': ''},
          'description': {'label': 'Description', 'width': '60', 'align': '', 'format': ''},
          'country.codcountry': {'label': 'Country Code', 'width': '60', 'align': '', 'format': ''},
          'country.description': {'label': 'Country', 'width': '60', 'align': '', 'format': ''}
    };
    headerColumns = this.columns.concat(['actions']);
    displayedColumns = this.headerColumns;
}

and the template used is as follows:

<mat-table [dataSource]="dataSource" matSort matSortActive="description" matSortDirection="asc"
                 matSortDisableClear>
        <ng-container [cdkColumnDef]="column" *ngFor="let column of columns">
          <mat-header-cell *matHeaderCellDef mat-sort-header>{{labelColumns[column].label}}</mat-header-cell>
          <mat-cell *matCellDef="let element"> {{element[column]}} </mat-cell>
        </ng-container>
        <!-- Column Definition: actions -->
        <ng-container matColumnDef="actions">
          <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
          <mat-cell *matCellDef="let row; let i=index;">
            <div class="actions">
              <button mat-icon-button [matMenuTriggerFor]="menu" aria-label="Open basic menu"
                      [disabled]="!permiso.is_edit && !permiso.is_remove">
                <mat-icon>more_vert</mat-icon>
              </button>
              <mat-menu #menu="matMenu">
                <button mat-menu-item (click)="openPopUp(row, row.idprovincia)"
                        *ngIf="permiso.is_edit">
                  <mat-icon>edit</mat-icon>
                  <span>Edit</span>
                </button>
                <button mat-menu-item (click)="eliminarProvincia(row)"
                        *ngIf="permiso.is_remove">
                  <mat-icon>delete</mat-icon>
                  <span>Delete</span>
                </button>
              </mat-menu>
            </div>
          </mat-cell>
        </ng-container>
        <mat-header-row *matHeaderRowDef="displayedColumns;"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>

      </mat-table>

The diagram displaying the data structure can be viewed here:

https://i.stack.imgur.com/pWHHo.png

In order to access specific attributes of the country object in the row data, such as 'country.codcountry', you may need a different approach considering how the keys are defined within the component's array. Hope that helps.

columns = ['codprovince', 'codprovinciasc', 'description', 'country.codcountry', 'country.description'];

Answer №1

In JavaScript, you have the flexibility to access properties directly without always using brackets ([]). For example, you can access results.pais, and then proceed to access its nested properties like results.pais.codpais or results["pais"]["codpais"].

The main scenario where using brackets becomes necessary is when accessing properties dynamically, as shown below:

var property = "codpais"

console.log(results.pais[property])

If you need to recursively iterate through an object using a string representation like "deepObject.deepProperty" starting from object (object.deepObject.deepProperty), you can split the string by dots and implement a function like this:

function iterateObject(object, key) {
  var property = key
  var properties = key.split('.')

  if (!!properties && properties.length > 0) {
    property = properties[0]

    // Handle cases with empty strings like `property.`
    if (!!properties[1]) {
      const nextProperties = key.replace(property, '')

      return iterateObject(object[property], nextProperties)
    }

    return object[property]
  }

  return object[property]
}

Alternatively, for ES6 users, here's a concise one-liner solution:

function iterateObject(object, key) { 
  return key.split('.').reduce((r, p) => (r[p] || r), object)
}

You can utilize it like this:

iterateObject(results, 'pais.codpais')

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

A small computation

How can I modify this code to calculate the total price #ttc by multiplying #totalcout with #marge Currently, I am able to add amounts when checkboxes are clicked, but I am struggling with integrating the multiplication for calculating the Total Price (TT ...

What is the best way to detect and handle the destroy event in Kendo UI grids when a click event

How can I trigger a function when the delete button in a grid is clicked using JavaScript? ...

Encounter an Internal Server Error while using Laravel 5.4

I am encountering an issue while attempting to implement ajax search in my laravel project. I have included the controller and JavaScript code related to this problem below. Can you please take a look and let me know what may be causing the error? pu ...

Switch the cursor to display the magnifying glass icon for zooming in and out

I am curious about how to modify the cursor shape to display a zoom in and zoom out symbol. Changing the cursor to indicate busy or wait status is something I am familiar with, document.manual_production.style.cursor='wait'; However, I am unsu ...

When you try to upload an image using php/ajax, it causes the page to refresh

I'm currently experiencing an issue with my script. I am successfully using formData() to upload an image via Ajax, which is being saved to the designated folder. However, I am puzzled as to why my page keeps refreshing after move_uploaded_file() is e ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

Angular and Bootstrap do not support margin styles

While working with Angular 5 and Bootstrap, I have encountered an issue with using inline styles for margin. The template I am using is as follows: @Component({ selector: "dynamic-container-component", template: ` <div styl ...

Retrieve the current URL upon page load

I'm currently attempting to parse the URL in document.ready() so I can retrieve the id of the current page and dynamically populate it with content from an AJAX call. However, I've encountered an issue where 'document.URL' seems to refe ...

delay in displaying options when toggling visibility in a dropdown menu

When you first click on the select, it displays incorrectly https://i.sstatic.net/Ax9T7j8J.png But when you click on it a second time, it displays correctly https://i.sstatic.net/UpW4krED.png $(document).on("click", "#edit_afpDetalle_mes&q ...

The functionality of data binding becomes unclear when the ngif directive is applied to a mat-selection-list in

I am facing an issue with displaying a mat-selection-list based on a condition. Since adding the ngif condition, the data is consistently being set to undefined. I am struggling to identify the root cause of this problem. Thank you in advance for your assi ...

Angular: Do Modules or Components Represent Pages in an Application?

Is it better to have a separate module for each page or a separate component for each page? What are the benefits of using one module for an entire site and loading different components for page transitions? ...

Is it necessary for me to be concerned with clearing out sizable objects in Node.js, or should I trust the garbage collector to handle

Recently, I encountered a memory issue with my node.js API while hosting it on Heroku's free version with only 512MB RAM. As the traffic increased over the weekend, I started receiving memory errors from Heroku due to exceeding limits. Despite searchi ...

Customizing modal window HTML in ng-bootstrapNeed to override the default modal window

Currently, I am utilizing ng-bootstrap to create my modals. I have been pondering the most effective approach to customize the modal window's HTML. The default appearance of the modal html is somewhat like this: <div role="document" class="modal- ...

Elevating the Material Design Lite Progress bar using ReactJS

I currently have MDL running with React and it appears to be functioning properly. The Progress Bar is displaying on the page as expected, loading with the specified progress on page load when a number is entered directly: document.querySelector('#qu ...

Stopping npm build when ESLint detects warnings

Dealing with a particularly immature team, I am determined to make the react-typescript build fail whenever ESLint issues warnings. src/modules/security/components/ForgotPasswordBox/index.tsx Line 8:18: 'FormikHelpers' is defined but never use ...

Numerals for Central Leaflet Marker

Is there a way to effectively center numbers inside markers? Here is the current situation: View Marker with Number How to Create a Marker return L.divIcon({ className: "green-icon", iconSize: [25, 41], iconAnchor: [10, 44], popupAn ...

Count up with style using the "jQuery Boilerplate" plugin for Jquery!

I am a beginner in creating jQuery plugins. The following jQuery plugin has been created using jQuery Boilerplate. It performs a count-up and notifies when the count-up is completed. I would like to have a function that restarts the count-up by setting t ...

When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead. With ...

Obtain the count of unique key-value pairs represented in an object

I received this response from the server: https://i.stack.imgur.com/TvpTP.png My goal is to obtain the unique key along with its occurrence count in the following format: 0:{"name":"physics 1","count":2} 1:{"name":"chem 1","count":6} I have already rev ...

Utilizing JavaScript, HTML, and CSS to incorporate images within circular frames

After finding inspiration from this question about rotating objects around a circle using CSS, I decided to modify the code to include images of Earth orbiting the Sun. The challenge was to make one image orbit another like a planet circling its star. Ear ...