0
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.

1
  • 3
    map over the array and return an array of objects using the iterated element as the employeeId value. Then stringify it to get JSON. Commented Dec 5, 2022 at 22:26

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Why var and not const ?
I moved your code into a runnable snippet so others can run and verify how it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.