【问题标题】:Pasting array of JSON into typescript array将 JSON 数组粘贴到打字稿数组中
【发布时间】: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;

错误:

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

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

感谢和问候

【问题讨论】:

    标签: arrays json typescript ionic2


    【解决方案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)
    猜你喜欢
    • 2022-11-19
    • 2020-12-27
    • 2018-06-14
    • 2018-09-18
    • 2021-12-19
    • 2018-04-26
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多