更新json数组中的null obect

时间:2017-02-06 07:39:58

标签: javascript angularjs

更新json数组中的空对象。

我曾尝试过使用map,但没有为所有json对象更新

我有一个像下面这样的json数组

var response =
{
  "code": null,
  "message": "Total 1 records found",
  "result": {
    "ordersList": [
      {
        "testId": 134,
        "ordersDto": {
          "orderId": 51684,
          "reportses": [
            {
              "reportId": 472,
              "reportStatus": {
                "id": 10,
                "value": "Pending",
                "prevId": 9,
                "type": "R"
              }
            }
          ]
        }
      },
      {
        "testId": 134,
        "ordersDto": {
          "orderId": 51687,
          "reportses": [

          ],

        }
      },
      {
        "testId": 134,
        "ordersDto": {
          "orderId": 51689,
          "reportses": [

          ],

        }
      },

    ]
  }
}

如果reports为null,那么我需要更新数组中所有JSON对象的报告状态

New Object =  "reportStatus": {
                "id": 10,
                "value": "Pending",
                "prevId": 9,
                "type": "R"
              }

在heupdate之后,它将返回一个状态为的数组。

var response =

{
  "code": null,
  "message": "Total 1 records found",
  "result": {
    "ordersList": [
      {
        "testId": 134,
        "ordersDto": {
          "orderId": 51684,
          "reportses": [
            {
              "reportId": 472,
              "reportStatus": {
                "id": 10,
                "value": "Pending",
                "prevId": 9,
                "type": "R"
              }
            }
          ]
        }
      },
      {
        "testId": 134,
        "ordersDto": {
          "orderId": 51687,
          "reportses": [
            {
              "reportStatus": {
                "id": 10,
                "value": "Pending",
                "prevId": 9,
                "type": "R"
              }
            }
          ],

        }
      },
      {
        "testId": 134,
        "ordersDto": {
          "orderId": 51689,
          "reportses": [
            {
              "reportStatus": {
                "id": 10,
                "value": "Pending",
                "prevId": 9,
                "type": "R"
              }
            }
          ],

        }
      },

    ]
  }
}

2 个答案:

答案 0 :(得分:1)

尝试此代码(未经测试)

response.result.ordersList.map(function(order){ 
  if(order.ordersDto.reportses.length === 0){ 
    order.ordersDto.reportses.push(newObjYouWantToPush) 
  }  
})

答案 1 :(得分:0)

此JavaScript代码段将帮助您实现解决方案。要找到数组的大小,并在大小为零时推送相应的内容。



for (i = 0; i < response.result.ordersList.length; i++) {
  if(response.result.ordersList[i].ordersDto.reportses.length === 0)
{
response.result.ordersList[i].ordersDto.reportses.push({
      "reportStatus": {
        "id": 10,
        "value": "Pending",
        "prevId": 9,
        "type": "R"
      }
    });
  }
}
&#13;
&#13;
&#13;