简体   繁体   中英

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

USE CASE: I need to create JSON data with the following structure dynamically from the formData in ANgular.

Required JSON Structure

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

So far I have managed to create like this.

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

With this code:

    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
        }
    }

How can I add more elements inside variables:{} like the required JSON structure?

I tried creating element as an array but that leaves index numbers inside the parameter.

Instead of forEach you can use reduce method like that

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;
}, {})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM