typescript Angular2 映射对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45174459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:43:57  来源:igfitidea点击:

Angular2 mapping object properties

angulartypescript

提问by SBB

Apologies for this probably super confusing title, I don't know if its exactly accurate with what I am trying to do.

为这个可能超级令人困惑的标题道歉,我不知道它是否与我想要做的完全准确。

I have a component that is assigning objects of data to variables so that they can be typecast. I have interfaces created for this purpose:

我有一个组件将数据对象分配给变量,以便它们可以是typecast. 我为此目的创建了接口:

export interface Role {
    RoleID: number;
    RoleName: string;
}

export interface Language {
    LanguageID: number;
    LanguageName: string;
}


...

roles: Role[] = [];
languages: Language[] = [];

I am using an npm module called ng-selectwhich adds some extended functionality to select inputs.

我正在使用一个名为ng-select的 npm 模块,它添加了一些扩展功能来选择输入。

My HTML is set up like so:

我的 HTML 设置如下:

<ng-select 
 [allowClear]="true"
 [items]="roles"
 placeholder="No role selected">
</ng-select>

All of my select inputs use an ID (value) and Label (text). This is great because the module allows for that.

我所有的选择输入都使用 ID(值)和标签(文本)。这很棒,因为该模块允许这样做。

Array of items from which to select. Should be an array of objects with id and text properties.

要从中选择的项目数组。应该是具有 id 和 text 属性的对象数组。

My question is as follows: The object that this module is wanting is needed the property names to be idand text. Since I am typing my inputs to the interface though, I am unable to rename them in there.

我的问题如下:这个模块想要的对象需要属性名称为idtext。由于我正在向界面输入我的输入,因此我无法在那里重命名它们。

Are there any suggestions on how I can map this data in a way where I can provide the module my object and say that RoleID = idand RoleName = textfor example.

是否有任何关于如何以我可以提供模块我的对象的方式映射这些数据并说出来的建议RoleID = idRoleName = text例如。

In short, my current object of:

简而言之,我目前的目标是:

{
    RoleID: 123,
    RoleName: 'Admin'

}

Needs to be:

需要是:

{
    id: 123,
    text: 'Admin'

}

回答by Alexander Staroselsky

You can bind the [items]attribute to a method of the component class that returns an array of transformed objects using Array.prototype.map:

您可以将该[items]属性绑定到使用Array.prototype.map返回转换对象数组的组件类的方法:

HTML:

HTML:

<ng-select 
 [allowClear]="true"
 [items]="roleItems"
 placeholder="No role selected">
</ng-select>

TS:

TS:

roleItems: Role[] = [];

getRoles(): Role[] {
    this.roleItems = this.roles.map((role: Role) => {
        return { id: role.RoleID, text: role.RoleName };
    });
}

Update:Here is a plunkerdemonstrating the functionality in action with a simple list and ngFor.

更新:这是一个plunker,用一个简单的列表和ngFor.