Make necessary changes to empty objects within a JSON array

Modify the null objects in a JSON array.

I attempted to use map, but it did not update all the JSON objects.

Here is an example of a JSON array:

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 the 'reports' property is null, then I need to update the 'reportStatus' for all the JSON objects in the array with the following details:

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

After the update, the array will return with the updated 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 №1

Check out this code snippet (Note: This code has not been tested)

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

Answer №2

This handy JavaScript code snippet will assist you in solving your problem. The key is to determine the size of the array and add the necessary content if the size is zero.

for (let 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"
      }
    });
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular routes cause a glitch in the Bootstrap navbar, causing it to shift to the left on certain active

Apologies for the simple question, I am new to web design and couldn't find a solution even after extensive googling and searching. The issue I am facing is that when clicking on "EX5" or "EX6" in my navbar, it shifts to the left side of the screen i ...

Looking for a custom textured circle in three.js?

Is there a way to create a circle with a texture on one side in three.js without using sprites? I was considering using THREE.CylinderGeometry, but I'm unsure of where to add the "materials" in the new THREE.CylinderGeometry(...) section. Any suggest ...

Emberjs 1.0: Data Changes don't Refresh Computed Property and Template

In my Ember.js application, I am using a datepicker which is integrated for selecting dates. When a date is clicked on the datepicker, a computed property should compare the selected date with the dates available in the timeslot to check for a match. Based ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

How can I terminate a parent function in NodeJS when inside a virtual function?

Here is something similar to the code snippet below: var async = require(async) function start () { async.series( [ function (callback) { // do something callback(null, "Done doing something") ...

The sidebar stays fixed in place and doesn't adapt to varying screen resolutions

Check out my website at . I have a fixed, blue sidebar on the left side of the page to ensure its content is always visible. However, I'm facing an issue with smaller resolutions like 1024x768 where some bottom content is cut off. How can I adjust the ...

Attempting to loop through a list and create a retrieval function for each item

My goal is to loop through the style tags and create a GET function for each one. The issue I'm facing is that the GET function is being written with a direct reference to 'styleTags[i]' instead of converting it to the appropriate tag. var ...

Retain selected choices even after refreshing the page using PHP

Working on a smaller project using PHP, I encountered a problem that has left me feeling lost. Let me break it down into two parts. Part 1: In my project, I have an index.php file and a getitem.php file. The index file contains a form with multiple select ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Problems encountered when transferring information from jQuery to PHP through .ajax request

Hey there! I am currently working with Yii and facing an issue while trying to pass some data to a controller method called events. This is how my jQuery ajax call looks like: var objectToSend = { "categories" : [selectedOption],"datefrom" : month + "" + ...

What is the process for setting up nested routes using React router?

I have multiple layouts that need to display different screens. Each layout has its own header, footer, and other shared elements similar pages should have. Below is the code I have created: <BrowserRouter> <Route path={['/index', &ap ...

Utilizing jQuery functions within Vue components in Quasar Framework

I've recently started delving into web app development and I'm encountering some basic questions regarding jQuery and Vue that I can't seem to find answers to. I have an application built using the Quasar Framework which frequently involves ...

Unable to set a default value for a select control using a custom directive

I am facing a simple scenario with a custom directive in AngularJS. In this case, if there is only one item in the drop-down menu, it should be selected by default; otherwise, it should function as a normal drop-down list. For this situation, I attempted ...

Getting a surprise image from the collection

I am experiencing an issue with retrieving images from an array. I have an array containing 6 variables that represent the paths to the images. However, when I use console.log at the end, it returns a random variable like sk11, sk15, etc., which do not c ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

Measuring Page Loading Status using Ajax

I'm still learning Ajax and JQuery, and I've been having a tough time putting this together. My goal is to use ajax navigation to load URLs and implement back and front navigations with popstate. The code below is functional, but I'm facing ...

Exploring the angular js repeater component's context menu options

In one of my current projects, the client has specifically requested a right-click menu feature. However, the challenge lies in ensuring that the function triggered by the menu options has access to relevant information from the model. For instance, you ...

Customized Box with MaterialUI Styling

Currently, I am utilizing Material UI 5 for my project. To avoid repeatedly defining the same sx prop every time I create a box, I aim to build a custom box component that ensures all boxes have a consistent appearance. Upon going through the documentation ...

Tips for updating the CSS properties of the "html" element

html { width:100%; } Looking to dynamically update the CSS of the html tag upon button click using JavaScript. The goal is to modify the existing HTML CSS code as shown below, but achieving this dynamically with a script. Is it possible? html { w ...