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>