2017-06-12 88 views
0

我有一個REST API,它包含JSON格式的數據。我將它存儲在一個對象數組中。但是我想爲每個對象附加一個NEW EMPTY數組。我無法做到。 以下是我的REST API的外觀。我在註釋中標記了我想要添加的每個對象的新數組。typescript angular2:如何將數組追加到數組中的每個對象?

 content = [ 
      { 
      text: 'abc', 
      options: [ 
       { 
        Id: 1, 
        Text: 'aaa' 
       }, 
       { 
        Id: 2, 
        Text: 'bbb' 
       }, 
       { 
        Id: 3, 
        Text: 'ccc' 
       }], 
// ARRAY[] 

    }, 
      { 
      text: 'def', 
      options: [ 
       { 
        Id: 21, 
        Text: 'qwerty' 
       }, 
       { 
        Id: 22, 
        Text: 'zxcv' 
       }, 
       { 
        Id: 23, 
        Text: 'asdf' 
       }], 
    // ARRAY[] 
      } 
     }] 

這是我試過的。

public newarr:Array<any>; 
this.httpservice.post('RESTUrl').subscribe(resp=>{ 
    this.contents = resp.data; 
    this.contents.forEach((x:any)=>{ 
     x.push(this.newarr); 
    }); 
    console.log("contents",this.contents); 
     }); 

回答

1

它看起來就像你試圖把一個數組到一個對象,它應該是x.NewArray = this.newarr什麼的。

1

所有你需要做的就是添加只是使用點符號。

this.httpservice.post('RESTUrl').subscribe(resp=>{ 
    this.contents = resp.data; 
    this.contents.forEach((x:any)=>{ 
    x.<value_name> = this.newarr; 
    }); 
    console.log("contents",this.contents); 
}); 

這樣它會將您的變量追加到數組。

+0

非常感謝。它可以工作。但是對於數組,它也是一樣的嗎? –

+0

是的,你也可以添加數組 –

+0

這是相同的方式還是我需要這樣寫:x.arr [] = this.newarr? –

相關問題