从对象数组获取数据

时间:2020-08-05 20:03:18

标签: arrays angular typescript

从对象数组获取数据时遇到问题。我的数据数组是这样的。

enter image description here

我只想获取列表menuCode

组件

ngOnInit() {
    this.commonService.menuList$.subscribe(data => {
      this.menuCode =  data;
      console.log(this.menuCode)
     })
  }

如果我添加像这样的代码this.menuCode = data['menuCode'],则会收到此错误TypeError: Cannot read property 'menuCode' of null。我应该怎么做才能得到menuCode列表。

编辑

服务

_getMenu() {
    this.loading.present();
    this.auth.getMenu()
    .pipe(take(1))
    .subscribe(
      res => {
        this.menuList$.next(res['menuList']);
        this.loading.dismiss();
      },
      error => {
        this.menuList$.next([]);
        this.loading.dismiss();
      }
    )
  }

1 个答案:

答案 0 :(得分:2)

您的res对象是一个对象数组。因此,res['menuCode']将返回null,因为它在数组中不存在。因此,如果要获取menuCode的列表,可以使用map()函数

_getMenu() {
    this.loading.present();
    this.auth.getMenu()
    .pipe(take(1))
    .subscribe(
      res => {
        this.menuList$.next(res.map(r => r.menuCode)); // here
        this.loading.dismiss();
      },
      error => {
        this.menuList$.next([]);
        this.loading.dismiss();
      }
    )
  }

相关问题