我在mockapi喜欢
的json[{"id":"1","name":"Container 1","widgets":[],{"id":"2","name":"Container 2","widgets":[]},{"id":"3","name":"Container 3","widgets":[]}]
我希望如下:
[{"id":"2","name":"Container 2","renamed":"true","widgets":[]},{"id":"1","name":"Container 1","renamed":"true","widgets":[]},{"id":"3","name":"Container 3","renamed":"true","widgets":[]}]
我尝试清除json(循环删除)并在上面发布json,结果是:
[{"0":{"id":"2","name":"Container 2","renamed":"true","widgets":[]},"1":{"id":"1","name":"Container 1","renamed":"true","widgets":[]},"2":{"id":"3","name":"Container 3","renamed":"true","widgets":[]},"id":"4","widgets":[],"renamed":"true"}]
但我想要完全像:
[{"id":"2","name":"Container 2","renamed":"true","widgets":[]},{"id":"1","name":"Container 1","renamed":"true","widgets":[]},{"id":"3","name":"Container 3","renamed":"true","widgets":[]}]
mockapi 中的
我的ts档案:
updateLocationContainer(){
/* loop delete all json */
/* this.containers is Json */
for (let i = 0; i < this.containers.length; i++) {
this.containerService.delete(this.containers[i].id).subscribe(result => {},(response: Response) => {
if (response.status === 500) {
this.error = 'errorHasOcurred';
}
});
} /*end for*/
this.containerService.createContainer(this.containers).subscribe(result => {
return this.containerService.getContainer().subscribe(res => this.containers = res);
},(response: Response) => {
if (response.status === 500) {
this.error = 'errorHasOcurred';
}
});
} /*end func */
我的服务:
delete(id){
const url = `${this.containerUrl}/${id}`;
return this.http.delete(url,{headers: this.headers})
.map(response => {
return response;
}).catch(error => this.handleError(error));
}
createContainer(container) {
return this.http.post(this.containerUrl,JSON.stringify(container),{headers: this.headers})
.map(response => {
return response;
}).catch(error => this.handleError(error));
}
答案 0 :(得分:0)
如果你使用forcícle执行一个函数,如下所示:
for(let i = 1; i < this.containers.length; i++){
this.containers.find(x => x.id == i).id = i++;
this.containers.find(x => x.id == i).renamed = true;
}
答案 1 :(得分:0)
如果你只想交换两个元素,你可以例如将索引0
的对象暂时存储在一个变量中,用索引1
中的对象覆盖数组中的对象然后设置暂时存储在索引1
中的对象:
data = [
{"id":"1","name":"Container 1","widgets":[]},
{"id":"2","name":"Container 2","widgets":[]},
{"id":"3","name":"Container 3","widgets":[]}
]
// ...
let temp = this.data[0];
this.data[0] = this.data[1];
this.data[1] = temp;