【问题标题】:How to create JSON data with custom structure in a custom structure in Angular如何在 Angular 的自定义结构中创建具有自定义结构的 JSON 数据
【发布时间】: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


【解决方案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;
}, {})

【讨论】:

  • 是的。这也有效。不得不稍微调整一下。将其包装在变量中:{ ...parameters}
  • 使用 reduce 代替 forEach 有什么大的不同吗?
  • forEach 只会循环遍历元素,reduce 使您能够合并每次迭代的结果并返回合并后的结果。但这仍然取决于您的使用情况。
  • 好的,很好。感谢您的信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
相关资源
最近更新 更多