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

时间:2021-03-11 12:36:42

标签: javascript json angularjs angular typescript

用例:我需要从 Angular 中的 formData 动态创建具有以下结构的 JSON 数据。

所需的 JSON 结构

df.pivot_table(values=["rent"], index=["city"], columns=["rooms"])

到目前为止,我已经成功地创建了这样的内容。

{
        "variables": {
            "phone": {
                "value": "1234567890",
                "type": "String"
            },
            "email": {
                "value": "9876543210",
                "type": "String"
            }
        }
    }

使用此代码:

    {
    "variables": {
        "phone": {
            "value": "1234567890",
            "type": "String"
        }
    }
}

如何在变量中添加更多元素:{} 就像所需的 JSON 结构一样?

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

1 个答案:

答案 0 :(得分:1)

你可以使用 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;
}, {})
相关问题