javascript - 需要格式化 JSON 输出以便与我的后端服务兼容
问题描述
我有一个像这样的表单的 JSON 输出
{
"testRefs": {
"testCd": null,
"testIndicator": null,
"testInd": null,
"testiolInd": null
},
"testList": {
"testname": null,
"testcode": null
},
"testCd": "someStrinf",
"testNm": "someString"
}
我需要将表单输出格式化为
{
"testRefs": [
{
"testCd": null,
"testIndicator": null,
"testInd": null,
"testiolInd": null
}],
{
"testList": [
{
"testname": null,
"testcode": null
}
],
"testCd": "someStrinf",
"testNm": "someString"
}
]
}
与后端服务兼容
如何添加数组符号
解决方案
您可以使用for..in并检查键的长度obj[key]
是否大于 1,只需将其添加到数组中,否则保持不变。
let obj = { "testRefs": { "testCd": null,"testIndicator": null,"testInd": null,"testiolInd": null},"testList": {"testname": null,"testcode": null},"testCd": null,"testNm": null}
for(let key in obj){
if(Object.keys(obj[key]||[]).length > 1){
obj[key] = [obj[key]]
}
}
console.log(obj)
推荐阅读
- python - 尝试使用 python 客户端库 pyarrow 连接 HDFS,但出现错误 FileNotFoundError。如何解决此问题并连接到 HDFS?
- microsoft-graph-api - 如何使用 Graph API 获取 SharePoint Online 列表项附件?
- c++ - 访问不同网站后如何获取完整(准确)的 Url / QUrl 地址?
- sql-server - 如何在 SQL SERVER 2017 SSMS 中用以前保存的行值替换行值
- postgresql - 从工作日(周一至周日)及其周日期(该周之间的任何日期)获取日期
- java - 通过捕获失败步骤的失败原因,继续执行 Serenity Jbehave BDD 中的后续步骤
- object - 使用英特尔实感进行对象检测
- azure - 通过 PowerShell 获取 Azure 中资源的资源创建者
- javascript - 不使用 Safari 浏览器加载 CSS
- java - 带有枚举的通用输入参数编译错误