2017-06-12 89 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? –

相关问题