需要格式化JSON输出以便与我的后端服务兼容

时间:2019-03-08 02:20:29

标签: 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"
    }
  ]
}

与后端服务兼容

如何添加数组符号

1 个答案:

答案 0 :(得分:0)

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