如何在 Angular 中的自定义结构中创建具有自定义结构的数据 JSON

How to create JSON data with custom structure in a custom structure in Angular

用例: 我需要从 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 结构?

我尝试将元素创建为数组,但在参数中留下了索引号。

您可以使用 reduce 方法代替 forEach

const parameters = Object.keys(this.sampleForm.value).reduce((prev,curr)=>{
   prev[curr] = { 
      value: this.sampleForm.value[curr],
      type: typeof this.sampleForm.value[curr] // not sure about that.
    }
   return prev;
}, {})