angular6實現物件轉換陣列物件
阿新 • • 發佈:2018-11-29
1 使用表單獲取到資料以後,是物件型別的資料如下圖
而後臺需要返回的資料是這種key:value的形式傳入
2 廢話不多說直接上程式碼(程式碼只擷取部分,僅供參考跑不起來,最後又一個小demo可以執行)
public discountArr = []; // 折扣陣列容器 public discountContent = { 'name': '', 'value': '' }; // 折扣轉換物件容器 public setDiscount = {}; // 折扣返回資料 ngOnInit() { // 頁面初始化傳送請求獲取資料折後this.service.getProductDiscount(this.userId).subscribe(data => { if (data.code !== 0) { // TODO 錯誤處理 console.log(data.message); } else { 返回成功後把獲取到的資料賦值給頁面的資料 console.log(data, '折扣'); this._discount.EIP = data.result.EIP; this._discount.EBS = data.result.EBS;this._discount.ECS = data.result.ECS; this._discount.SLB = data.result.SLB; this._discount.OSS = data.result.OSS; this._discount.CPS = data.result.CPS; this._discount.CAAS = data.result.CAAS; this._discount.VPC = data.result.VPC; this._discount.SBW = data.result.SBW;this._discount.RDSMysql = data.result.RDSMysql; this._discount.CDN = data.result.CDN; } }); // 表單獲取到的資料 this.discount = this.fb.group({ EIP: [10, [Validators.required]], EBS: [9, [Validators.required]], ECS: [null, [Validators.required]], SLB: [null, [Validators.required]], OSS: [null, [Validators.required]], CPS: [null, [Validators.required]], CAAS: [null, [Validators.required]], VPC: [null, [Validators.required]], SBW: [null, [Validators.required]], RDSMysql: [null, [Validators.required]], CDN: [null, [Validators.required]], }); console.log(this.discount.value); } // 表單提交執行函式 onSubmit() { // tslint:disable-next-line:forin // 迴圈表單獲取的資料 for (const key in this.discount.value) { // 每次執行行前讓新物件為空 this.discountContent = { 'name': '', 'value': '' }; // 如果為空的話 if (!this.discountContent[key]) { // 把拆分開的資料分別放入key value this.discountContent.name = key; this.discountContent.value = this.discount.value[key]; } // 每次拆分成功插入陣列 this.discountArr.push(this.discountContent); } // 轉換成後臺需要的資料格式 this.setDiscount = { operatorId: this.marketId, discount: this.discountArr, }; console.log(this.setDiscount); // 傳送修改記錄 this.service.changeProductDiscount(this.userId, this.setDiscount).subscribe(data => { if (data.code != 0) { // TODO 錯誤處理 this.notification.create(`error`, '失敗', data.message); } else { this.notification.create(`success`, '成功', '折扣已修改成功'); } }); }
3 資料轉換 demo 示例 (這個可以跑)
<!DOCTYPE html> <html> <head> <title></title> </head> <body> </body> <script type="text/javascript"> var json = { "CAAS":10, "CDN": 10, "CPS": 10, "EBS": 10, "ECS": 10, "EIP": 10, "OSS": 10, "RDSMysql": 10, "SBW": 10, "SLB": 10, "VPC": 10 }; var arr = []; var json1= {}; for(let key in json){ json1 = {}; if(!json1[key]){ json1.name = key; json1.value = json[key]; } arr.push(json1); } console.log(arr); </script> </html>