将 JSON 数组粘贴到打字稿数组中

Posted

技术标签:

【中文标题】将 JSON 数组粘贴到打字稿数组中【英文标题】:Pasting array of JSON into typescript array 【发布时间】:2017-09-23 01:30:02 【问题描述】:

我有一个 JSON 数组,想将它粘贴到 typescript 中的数组变量中。

我从http://www.example.com/select.php 收到的 JSON:

 
     "User":[ 
      "Name":"Luca M","ID":"1",
      "Name":"Tim S","ID":"2",
      "Name":"Lucas W","ID":"3" 
     ] 
    

我想要一个这样的数组:

  this.items = [
          'Luca M',
          'Tim S',
          'Lucas W'
        ];

编辑:

当前代码是

 this.http.post('http://www.example.com/select.php', creds, 
          headers: headers
      )
          .map(res => res.json().User) 

          .subscribe(
          data => this.data = data.User.map(user => user.Name), 
          err => this.logError(err),
          () => console.log('Completed')
          );


      this.items = this.data;

错误:

无法读取未定义的属性“地图”

我怎样才能意识到这一点?

感谢和问候

【问题讨论】:

【参考方案1】:

对于这个非常具体的 json:

const json = 
    "User": [
         "Name": "Luca M", "ID": "1" ,
         "Name": "Tim S", "ID": "2" ,
         "Name": "Lucas W", "ID": "3"  
    ] 


const items = json.User.map(user => user.Name);
console.log(items); // ["Luca M", "Tim S", "Lucas W"]

(code in playground)

【讨论】:

感谢您的建议,我忘了提及,我从 API 接收我的 JSON。你能根据我的编辑再帮我一次吗? 我试过 const json = JSON.stringify(this.data); this.items = this.data.map(user => user.Name);但这并没有像我预期的那样工作 你不需要stringify你的数据,如果你这样做,你最终会得到一个字符串而不是一个对象...... 好吧,有道理,但它也不起作用 this.items = this.data.map(User => User.Name); --无法读取未定义的属性“地图” 您可能正在执行异步操作。您需要等到完成。在subscribe 回调中执行该部分:data => this.data = data.User.map(user => user.Name)

以上是关于将 JSON 数组粘贴到打字稿数组中的主要内容,如果未能解决你的问题,请参考以下文章

将 JSON 对象转换/翻译为打字稿类型/接口的工具?

打字稿将数组转换为 JSON

将firebase json转换为打字稿数组

将 JSON 转换为数组打字稿

在打字稿中将 JSON 转换为字符串数组

在打字稿中解析 JSON 数组