access nested object with “n” level deep object using square bracket notation

这一生的挚爱 提交于 2020-12-10 13:20:13

问题


I want to take some config object to show some nested data.Here is the demo code

As it can be seen, "customer.something" is what I need to access. Now there could be 'N'level of nesting . The grid takes care of it using field='customer.something' . How to do the same using my template

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

Here is the HTML file:

<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> -->

回答1:


You could use a pipe to get the field value by the string path. Like this:

@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;
  }
}

and on the template:

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

Here's how it would look:

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

PS: I got the function to get the property value from the string path from this stackoverflow answer: Accessing nested JavaScript objects and arrays by string path

There are other ways to get it, maybe some is better.



来源:https://stackoverflow.com/questions/64911518/access-nested-object-with-n-level-deep-object-using-square-bracket-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!