首页 > 解决方案 > 需要格式化 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"
    }
  ]
}

与后端服务兼容

如何添加数组符号

标签: javascriptjson

解决方案


您可以使用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)


推荐阅读