user630209 user630209 - 4 years ago 90
AngularJS Question

Update null obects in a json array

Update null objects in a json array.

I had tried using map but it didn't updated for all the json objects

I had a json array like below

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": [

],

}
},

]
}
}


If reports is null, then I need to update the report status of all the JSON object in the array

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


After heupdate, it will return an array with the status.

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

}
},

]
}
}

Answer Source

Try this code ( It is not tested )

response.result.ordersList.map(function(order){ 
  if(order.ordersDto.reportses.length === 0){ 
    order.ordersDto.reportses.push(newObjYouWantToPush) 
  }  
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download