2

Consider the object below:

var item = {
  id: 'some-id',
  price: 12,
  customer: {
     id: 'fake-id',
     name: 'fake-name'
   }
};

We can access the customer name using "dots" or "brackets" as below:

  • item.customer.name
  • item['customer'].name
  • item.customer['name']
  • item.['customer']['name']

Question

In Javascript or Typescript, is there a way to access customer name like the following?

item['customer.name'] or item[customer.name]

Notes

In angular I created a reusable table component based on the mat-table, which includes pagination, sort filter and bunch of other functions... I use the following for the column definitions:

mytable.component.ts:

export interface MyTableCol {
    id: string;
    title: string;
    // some other settings...
}

mypage.component.ts:

cols: MyTableCol[] = [
  {id: 'price', title: 'Total Price'},
  {id: 'customer.name', title: 'Customer Name' }
];

mypage.component.html:

<my-table [columns]="cols"></my-table>

mytable.component.html:

<ng-container [matColumnDef]="col.id" *ngFor="let col of columns">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>
            {{ col.title}}
    </th>
    <td mat-cell *matCellDef="let element">
        {{ element[col.id] }}
    </td>
</ng-container>

However, for the nested properties (customer.name) this won't work. I think the reason is the line: element[col.id] converts to element['customer.id'] in case of the customer name column.

How can I resolve this?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
  • Looks related? [accessing-nested-javascript-objects-with-string-key](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – ASDFGerte Feb 21 '20 at 01:36
  • you can't do item['customer']['name'] ? or do you mean like element[col.id.split('.')[0]][col.id.split('.')[1]] ? kinda confused about the issue... – Matt Berg Feb 21 '20 at 01:45

1 Answers1

2

It won't work automatically to pass a string like that to access the properties, you need to create a getter function like lodash _get and use it to find the value you need. And then write something like:

{{ _getAtr(element, col.id) }}
Dvid Silva
  • 1,110
  • 13
  • 25