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.

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *