如何从元素的数组列表动态构建JSON ?


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


我不完全确定,因为我试图让我的头脑。下面是我不完整的实现:'

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

不知道如何动态创建JSON结构,后面跟着逗号分隔键/值。

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

相关内容

  • 没有找到相关文章

最新更新