如何在Angular TypeScript中忽略JSON数据中的变量

时间:2019-04-04 13:50:22

标签: json angular typescript angular7

在用角度7读取JSON文件时遇到问题。

下面是我的JSON数据文件的格式。

agg(f.first())

这是我的component.ts文件方法,在其中我为JSON文件调用服务。

[
   {
      "attributes":  {
        "User": "jay"
    }
},
   {
      "attributes": {
        "User": "roy"
    }
},
    {
      "attributes":{
        "User": "kiya"
    }
},
    {
      "attributes":{
        "User": "gini"
    }
},
   {
      "attributes": {
        "User": "rock"
    }
},
   {
      "attributes": {
        "User": "joy"
    }
}

]

这是我的service.ts文件方法。

        this.rest.getUsers().subscribe((data: {}) => {
            console.log(data);
            this.items = data;
            //this.items=data;
        });

现在,我只想从JSON文件中读取 private extractData(res: Response) { let body = res; return body || { }; } getUsers():Observable<any> { return this.httpService.get('./assets/usersdetails.json').pipe( map(this.extractData)); } ,并且想过滤单词User。有什么方法可以从JSON文件中过滤出该内容,所以我只能得到attributes。因为在我的项目中JSON中的User value造成了问题,我想忽略或过滤该问题。

因为在我的应用程序中,我需要读取以下格式的JSON。

attributes

但是数据以上述[ { "User": "jay" }, { "User": "roy" }, { "User": "kiya" }, { "User": "gini" }, { "User": "rock" }, { "User": "joy" } ]

的JSON格式出现

因此,在阅读时,有什么方法可以过滤来自JSON的多余attributes内容。

1 个答案:

答案 0 :(得分:1)

您没有显示extractData方法的代码,因此很难说什么不起作用,但是您应该可以通过以下方法实现目标。

return this.httpService
           .get('./assets/usersdetails.json')
           .pipe(
             map(data => data.map(d => d.attributes))
           );

如果“属性”上还有其他属性,而您实际上只需要“用户”数据,则可以进一步将代码更新为:

return this.httpService
           .get('./assets/usersdetails.json')
           .pipe(
             map(data => data.map(d => ({ 'User': d.attributes.User })))
           );