Angular 6-将数组属性转换为一组新数组

时间:2018-07-30 17:46:21

标签: angular

下面的代码将为我生成一组包含idtitle的数组,但是,我需要仅包含 title的数组。

 this.categoriesService.getCategories().subscribe(categories => {
   this.categories = categories as Category[];
 });

我该怎么做?

1 个答案:

答案 0 :(得分:2)

如果要字符串数组:

this.categoriesService.getCategories().subscribe(categories => {
   this.categories = categories.map(category => category.title);
});
// this.categories = ['title1', 'title2', 'title3',...]

如果要不包含id的对象数组:

this.categoriesService.getCategories().subscribe(categories => {
   this.categories = categories.map(category => {
     return {title: category.title};
   });
});
// this.categories = [{title: 'title1'}, {title: 'title2'}, {title: 'title3'},...]