2017-04-25 47 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

如果你這樣做,你不需要'串化'你的數據,如果你這樣做,你最終得到一個字符串,而不是一個對象... –