简体   繁体   English

使用方括号表示法访问具有“n”级深度对象的嵌套对象

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

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.可以看出, "customer.something"是我需要访问的。 Now there could be 'N'level of nesting .现在可能有“N”级嵌套。 The grid takes care of it using field='customer.something' .网格使用field='customer.something' How to do the same using my template如何使用我的template做同样的事情

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

Here is the HTML file:这是 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> -->

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 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 PS:我得到了从这个 stackoverflow 答案中的字符串路径中获取属性值的函数: 按字符串路径访问嵌套的 JavaScript 对象和数组

There are other ways to get it, maybe some is better.还有其他方法可以获得它,也许有些更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM