Iterating through the nested JSON causes an error when trying to set properties of undefined

My dataset is structured as a nested JSON, with the main object named bwaResult. Within this object, there are three primary groups: actBwa, fcBwa, and planBwa. Each of these groups contains yearly data and results that include years. I am trying to organize this data by assigning values to specific years, such as 2020, for each group.

In my code snippet:

 const plMonthResults = {};
        const plMonth = resp.success ? resp.bwaResult : null; // JSON-DATA
        delete resp.success;
        if (plMonth && plMonth !== null && Object.keys(plMonth)) {
          let count = 0;
          for (const bwaType in plMonth) {
            const plMonthData = plMonth[bwaType]; // Extracting actBwa, fcBwa, planBwa
            if (count === 0) {
              for (const yearKey of Object.keys(plMonthData)) {
                plMonthResults[yearKey] = {}; // Organizing data by years
              }
            }
            for (const yearKeyInPlMonth in plMonthData) {
              plMonthResults[yearKeyInPlMonth][bwaType] = plMonthData[yearKeyInPlMonth]; // Error occurs here
            }
            count += 1;
          }
        }

Unfortunately, when running the code, I encounter the following error:

ERROR TypeError: Cannot set properties of undefined (setting 'fcBwa')

I suspect that the issue arises from missing values for certain years within the different groups like fcBwa. Can someone guide me on how to resolve this issue?

Check out my progress on StackBlitz: https://stackblitz.com/edit/read-local-json-file-service-udqvck?file=src%2Fapp%2Fapp.component.ts

Answer №1

It appears that by using the count function, you are only copying the keys once, resulting in having only the keys of the first object (actBwa). To prevent overriding existing keys, you can iterate through the keys of each object and modify the code as follows:

       for (const yearKey of Object.keys(plMonthData)) {
          plMonthResults[yearKey] = plMonthResults[yearKey] ?? {};
        }

You may also integrate the check into the main loop instead of a separate one:

   for (const yearKeyInPlMonth in plMonthData) {
          plMonthResults[yearKeyInPlMonth] = plMonthResults[yearKeyInPlMonth] ?? {};
          plMonthResults[yearKeyInPlMonth][bwaType] = plMonthData[yearKeyInPlMonth]; 
        }

Please let me know if these adjustments provide the desired outcome.

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

Using jQuery, transform JSON into an array

After running my PHP code, I have the following result: $result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_ ...

Can someone explain the meaning of this code?

Recently, I came across a project where this line of code was used in a jQuery script. I'm not sure of its purpose and would appreciate some help understanding why it was included. If necessary, I can provide the entire function for reference. $("#ta ...

Guide on converting a string into an array by splitting with a comma separator in Android using Kotlin

I'm facing an issue with formatting the results retrieved from a Room database. The output appears as one long unbroken word, for example "texta,textb,textc", but I need them to be in a string array format like this: "texta"," ...

Converting Comma Separated Values to neatly organized JSON using Python

After struggling with my CSV file structure which looks like this: Store, Region, District, MallName, Location 1234,90,910,MallA,GMT 4567,87,902,MallB,EST 2468,90,811,MallC,PST 1357,87,902,MallD,CST I managed to reformat it with a lot of iteration into ...

Rendering EJS on the page even before the for loop is completed or the data is pushed to an

I'm facing a challenge where I need to display an array in HTML using EJS. However, the issue is that my EJS is rendering before any data gets pushed to the empty array, resulting in an empty array being displayed on the page. app.set('view engi ...

Steps to generate a JSON string as shown below

As an android developer who is new to PHP, I find myself struggling with the language. Below is the code snippet I have been working on: <?php header('Content-Type: application/json; charset=utf-8'); $mysqli = new mysqli ('localhost&apos ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...

AngularJS templateUrl versus template: what's the difference?

When it comes to routing, I believe that templateUrl is the preferred choice over template. However, when dealing with directives, the decision between using templateUrl or template can be a bit more nuanced. Some developers opt to include chunks of HTML i ...

The input field does not contain the chosen date

Utilizing the react-dates library from Airbnb for date selection has been a bit challenging in conjunction with redux form. Upon clicking the select date button, the calendar interface appears. However, upon choosing a date, the input box remains empty ins ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

Error encountered when running npm build in Vue.js: Conflict arises in bundle.css due to multiple chunks (app and chunk-f33d301e) emitting assets with the same filename

After uncommenting the CSS extracting method in the vue.config.js file and running a production build, I encountered the error mentioned above. // vue.config.js file // Uncomment before executing 'npm run build' css: { extract: { ...

The text entered in the textbox vanishes after I press the submit button

When a user selects a value in a textbox and clicks the submit button, the selected value disappears. <div class="panel-body" ng-repeat="patient in $ctrl.patient | filter:$ctrl.mrd"> <form> <div class="form-group"> ...

Javascript/Ajax not receiving ViewBag data properly

I've written the following script: <script> $("#sendMSG").click(function () { $.ajax({ type: "POST", url: '@Url.Action("Action", "Controller")', dataType: "JSon", data: { "Email": '@ViewBag.Ema ...

Issue with window resize directive not functioning as expected

I have recently crafted a personalized directive in AngularJS. Here's the code snippet: var esscom = angular.module('esscom',['ngMaterial' ,'ngMessages','ui.bootstrap','ui.router']); esscom.directiv ...

Discovering the result of the variable in a callback function within a Node

I am utilizing this specific NPM package to retrieve the CSV output of a table from an access database. The structure of my function is as follows: function createDatabase(mdbfile){ var rawDB = mdb(mdbfile); var db = {} rawDB.tables(function(err, ...

Invoke method from service on click in Angular 2

I'm facing an issue with a button component that should trigger a function on click event: <button pButton type="button" label="Add EchoBeacon" (click)="insertPoint()"> constructor(private mappaService: MappaService) {} ... insertPoint() { ...

I'm having trouble linking MikroORM migration to Postgresql - the npx command keeps failing. Can anyone offer some guidance on what

I am encountering a situation similar to the one described in this post. I'm following Ben Awad's YouTube tutorial: you can see where I am in the tutorial here. Objective: My goal is to execute npx mikro-orm migration:create in order to generate ...

The response from Ajax is being duplicated with each click

Upon clicking the "Add More" button, I dynamically display two dropdowns. The first dropdown is displayed instantly, while the second dropdown requires an Ajax call to fetch and display its content. The functionality of displaying the second dropdown also ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. https://i.sstatic.net/T9UKR.png Below is my API code: https://i.sstatic.net/kkwqs.png Here is the service code: https://i.sstatic.net/IUMSd.png This section ...

Pass data from PHP to JS after triggering AJAX communication

*Updated with full code example, after receiving feedback I decided to share a sample of the code that is giving me trouble. Essentially, I am trying to achieve the functionality where clicking on a link in the HTML will submit a form to called.php and dis ...