Home > Blockchain >  How to construct JSON dynamically from array list of elements?
How to construct JSON dynamically from array list of elements?

Time:12-06

I have a list of elements in an array: empIds: [38670, 38671, 38672, 38673]

I am trying to build a JSON that holds all these array elements in the payload:

    {
    
     "members": [
        {
            "EmployeeId": "38670"
        },
        {
            "EmployeeId": "38671"
        },
        {
            "EmployeeId": "38672"
        },
        {
            "EmployeeId": "38673"
        }
      ]
    }




I wasn't completely sure as I am trying to get my head around. Below is my incomplete implementation: `

     let parts = [];
                for(i=0;i<memberInternalIds.length; i  ){
                    if(memberInternalIds.length == 1){
                        parts ={participantId: memberInternalIds[0]}          
                    } else {
                        parts ={participantId: memberInternalIds[i]}  
                    }
                }

`

Not sure how to dynamically create JSON structure with followed by comma-separated key/values.

CodePudding user response:

const empIds = [38670, 38671, 38672, 38673];

let payload = { members: empIds.map(id => ({"EmployeeId": id})) };

// Convert the payload to a JSON string
const jsonStr = JSON.stringify(payload);

// Print the JSON string
console.log(jsonStr);

  • Related