2017-04-25 48 views
0

我有一个JSON数组,想将其粘贴到打字稿中的数组变量中。将JSON数组粘贴到打字稿数组中

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

{ 
    "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; 

错误:

Cannot read property 'map' of undefined

我怎么能意识到这一点?

感谢和问候

回答

2

对于这种非常具体的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

+0

感谢您的建议,我忘了提,我收到我的JSON从API。根据我的编辑,你能否再次帮助我? – dzitrus

+0

我试过 const json = JSON.stringify(this.data); this.items = this.data.map(user => user.Name); 但这并没有像我期望的那样工作 – dzitrus

+0

如果你这样做,你不需要'串化'你的数据,如果你这样做,你最终得到一个字符串,而不是一个对象... –