用"n"访问嵌套对象.使用方括号表示法来对深层对象进行级别调整 [英] access nested object with "n" level deep object using square bracket notation

查看:75
本文介绍了用"n"访问嵌套对象.使用方括号表示法来对深层对象进行级别调整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一些配置对象来显示一些嵌套数据.这是

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

可以看出,"customer.something" 是我需要访问的内容.现在可能有"N"级嵌套.网格使用 field ='customer.something'进行处理.如何使用我的 template

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>

这是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;
  }
}

并在模板上:

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

这是它的外观:

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

PS:我从该stackoverflow答案的字符串路径中获取了属性值:

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.

这篇关于用"n"访问嵌套对象.使用方括号表示法来对深层对象进行级别调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆