簡體   English   中英

使用方括號表示法訪問具有“n”級深度對象的嵌套對象

[英]access nested object with "n" level deep object using square bracket notation

我想拿一些配置對象來顯示一些嵌套數據。這是演示代碼

可以看出, "customer.something"是我需要訪問的。 現在可能有“N”級嵌套。 網格使用field='customer.something' 如何使用我的template做同樣的事情

<e-column field='customer.something' headerText='Other' editType='dropdownedit' [edit]='editParams' width=120>

這是 HTML 文件:

<ejs-grid #Grid [dataSource]='data' allowSorting='true'>
    <e-columns>
        <ng-template #colTemplate ngFor let-column [ngForOf]="colList">
            <e-column [field]='column.field' [headerText]='column.header' textAlign='Right' width=90>
                <ng-template #template let-data>
                    {{data[column.field] |  currency:'EUR'}} <-- want to fix this line
                </ng-template>
            </e-column>
        </ng-template>
    </e-columns>
</ejs-grid>

<!-- <ejs-grid #Grid [dataSource]='data' allowSorting='true'>
    <e-columns>
        <e-column field='price' isPrimaryKey='true' headerText='Price' textAlign='Right' width=90></e-column>
        <e-column field='customer.something' headerText='Other' editType='dropdownedit' [edit]='editParams' width=120>
        </e-column>
    </e-columns>
</ejs-grid> -->

您可以使用管道通過字符串路徑獲取字段值。 像這樣:

@Pipe({name: 'fieldFromPath'})
export class FieldFromPathPipe implements PipeTransform {
  transform(data: Object, property: string): Object {
    property = property.replace(/\[(\w+)\]/g, '.$1');
    property = property.replace(/^\./, '');
    var a = property.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in data) {
            data = data[k];
        } else {
            return;
        }
    }
    return data;
  }
}

並在模板上:

<ng-template #template let-data>
 {{data | fieldFromPath: column.field |  currency:'EUR'}}
</ng-template>

這是它的外觀:

https://stackblitz.com/edit/angular-ej2syncfusion-angular-grid-jqm2kz

PS:我得到了從這個 stackoverflow 答案中的字符串路徑中獲取屬性值的函數: 按字符串路徑訪問嵌套的 JavaScript 對象和數組

還有其他方法可以獲得它,也許有些更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM