英文:
how to get list of ids to string object with comma in angular
问题
我有一个下拉菜单,其中包含以下选项:
userList = [{ id: "0", name: "ALL" }, { id: "1", name: "Smith" }, { id: "2", name: "Smith" }, { id: "3", name: "RAM" }];
当选择"ALL"选项时,我需要将所有用户的ID转为字符串对象,不包括0。
string str = {1,2,3}(not include 0)
在我的Typescript代码中:
<mat-select placeholder="User" (ngModelChange)="modelChanged($event)" formControlName="user" name="user">
<mat-option *ngFor="let data of userList" [value]="data.id">{{ data.name }}</mat-option>
</mat-select>
我的Typescript代码如下:
onChangeRole(): void {
this.userRoleService.getUserDetails().subscribe((response: Response) => {
if (response.failure) {
this.modalPopupService.openPopup(AlertComponent, { message: response.error });
} else {
this.userList = response.result;
const all = {
id: 0,
name: 'ALL'
};
this.userList.splice(0, 0, all);
}
});
}
modelChanged(res): void {
const userType = res;
if (userType === 0) {
this.userType = ???;
} else {
this.userType = userType;
}
}
上面的this.userType
是一个属性。
如何将这些ID转为字符串对象?
英文:
I have drop down with
userList =[ { id: "0",name: "ALL"},{id: "1",name: "Smith"},{id: "2",name: "Smith"},{
id: "3", name: "RAM"}];
when select ALL option i need to get all id's of user into string object.
string str = {1,2,3}(not include 0)
<mat-select placeholder="User"(ngModelChange)="modelChanged($event)" formControlName="user" name="user">
<mat-option *ngFor="let data of userList" [value]="data.id">{{data.name}} </mat-option>
</mat-select>
my Typescrpt :
onChangeRole(): void {
this.userRoleService.getUserDetails().subscribe((response: Response) => {
if (response.failure) {
this.modalPopupService.openPopup(AlertComponent, { message: response.error });
} else {
this.userList = response.result;
const all = {
id: 0,
name: 'ALL'
};
this.userList.splice(0, 0, all);
}
});
}
modelChanged(res): void {
const userType = res;
if (userType === 0) {
this.userType = ???;
} else {
this.userType = userType;
}
}
Above this.usertype is any property.
How to get that list of ids into string object?
答案1
得分: 2
你可以使用filter
来筛选你的数组,然后再使用map
来提取id
属性:
userList.filter(f => f.id != zeroSymbol).map(({id}) => id);
一个示例:
let userList = [
{ id: "0", name: "ALL" },
{ id: "1", name: "Smith" },
{ id: "2", name: "Smith" },
{ id: "3", name: "RAM" }
];
const zeroSymbol = '0';
const resultArray = userList.filter(f => f.id != zeroSymbol).map(({id}) => id);
console.log(resultArray)
英文:
You can filter
your array and then map
just id
properties:
userList.filter(f => f.id != zeroSymbol).map(({id}) => id);
An example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let userList = [
{ id: "0", name: "ALL" },
{ id: "1", name: "Smith" },
{ id: "2", name: "Smith" },
{ id: "3", name: "RAM" }
];
const zeroSymbol = '0';
const resultArray = userList.filter(f => f.id != zeroSymbol).map(({id}) => id);
console.log(resultArray)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论