【发布时间】:2021-06-09 10:59:37
【问题描述】:
用例:我需要从 Angular 中的 formData 动态创建具有以下结构的 JSON 数据。
必需的 JSON 结构
{
"variables": {
"phone": {
"value": "1234567890",
"type": "String"
},
"email": {
"value": "9876543210",
"type": "String"
}
}
}
到目前为止,我已经设法创建了这样的东西。
{
"variables": {
"phone": {
"value": "1234567890",
"type": "String"
}
}
}
使用此代码:
this.parametres = {};
var element = {};
Object.keys(this.sampleForm.controls).forEach(key => {
console.log(key + " -- " + this.sampleForm.get(key).value);
element = {
[key]: {
"value": this.sampleForm.value[key],
"type": "String"
},
}
});
this.parametres = {
variables: {
...element
}
}
如何在变量中添加更多元素:{} 比如所需的 JSON 结构?
我尝试将元素创建为数组,但在参数中留下了索引号。
【问题讨论】:
-
您正在覆盖
element。尝试更新它。喜欢element[key] = ..
标签: javascript json angularjs angular typescript