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?
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) }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.