typescript angular2:如何将数组附加到数组中的每个对象?
我有一个RESTAPI,它包含JSON格式的数据。我将它存储在一个对象数组中。但是我想给每个对象附加一个新的空数组。我做不到。 下面是我的RESTAPI的样子。我标记了要为注释中的每个对象添加的新数组typescript angular2:如何将数组附加到数组中的每个对象?,angular,typescript,angular2-services,Angular,Typescript,Angular2 Services,我有一个RESTAPI,它包含JSON格式的数据。我将它存储在一个对象数组中。但是我想给每个对象附加一个新的空数组。我做不到。 下面是我的RESTAPI的样子。我标记了要为注释中的每个对象添加的新数组 content = [ { text: 'abc', options: [ { Id: 1, Text: 'aa
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);
});
public-newarr:Array;
this.httpservice.post('RESTUrl').subscribe(resp=>{
this.contents=resp.data;
this.contents.forEach((x:any)=>{
x、 推(this.newarr);
});
console.log(“contents”,this.contents);
});
看起来你想把一个数组推到一个对象上,它应该是x.NewArray=this.newarr
或者什么的。看起来你想把一个数组推到一个对象上,它应该是x.NewArray=this.newarr
或者什么的。你需要做的就是简单地使用点符号来添加
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);
});
this.httpservice.post('RESTUrl').subscribe(resp=>{
this.contents=resp.data;
this.contents.forEach((x:any)=>{
x、 =this.newarr;
});
console.log(“contents”,this.contents);
});
这样,它会将变量附加到数组中 你所需要做的就是简单地使用点符号进行添加
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);
});
this.httpservice.post('RESTUrl').subscribe(resp=>{
this.contents=resp.data;
this.contents.forEach((x:any)=>{
x、 =this.newarr;
});
console.log(“contents”,this.contents);
});
这样,它会将变量附加到数组中 非常感谢。它可以工作。但是对于数组也是一样的吗?是的,你也可以添加数组。是同样的方法还是我需要这样写:x.arr[]=this.newarr?你不需要添加
[]
。它会自动接受它。因为您所做的只是将数组附加到JSON数组变量,而不是Typescript变量。Nope。。当我这样说时,它对我不起作用:var newarr:Array=[];this.contents.forEach(x=>{x.arr=newarr;});但这是有效的:this.contents.forEach(x=>{x.arr=newarray(x.choices.length);});非常感谢。它可以工作。但是对于数组也是一样的吗?是的,你也可以添加数组。是同样的方法还是我需要这样写:x.arr[]=this.newarr?你不需要添加[]
。它会自动接受它。因为您所做的只是将数组附加到JSON数组变量,而不是Typescript变量。Nope。。当我这样说时,它对我不起作用:var newarr:Array=[];this.contents.forEach(x=>{x.arr=newarr;});但这是有效的:this.contents.forEach(x=>{x.arr=newarray(x.choices.length);});