I am encountering a problem where I lose the values of a nested array of objects when trying to push it into another array

My goal is to format data for use with the amCharts library. The required structure should look like this:

data = [{
  name: "First",
  total: 190,
  children: [
    {
        name: "A1",
        value: 100
    },
    {
        name: "A2",
        value: 60
    },
    {
        name: "A3",
        value: 30
    },
  ],
  name: "Second",
  total: 150,
  children: [
    {
        name: "B1",
        value: 100
    },
    {
        name: "B2",
        value: 30
    },
    {
        name: "B3",
        value: 20
    },
  ]
}]

The current prepared data looks like this:

const data = { 
  'Corporate Investors': {
  total: 7, // total number of 'Corporate Investors', not the sum total of 'stages'
  stages: {
    Seed: 7,
    'Series A': 7,
    'Series B': 7,
    'Series C': 7,
    'Series D': 7
    }
  },
  'Angel investor': {
   total: 11,
   stages: {
     Seed: 10,
     'Series A': 10,
     'Series B': 11,
     'Series C': 11,
     'Series D': 9
}...

To convert this object into an array suitable for amCharts, I have created a helper function based on one of their demos available at:

function processData(data) {

  const treeData = [];
  let typeData = {};

  // loops through the outer 'Angel investor' type-keys
  for (const key of Object.keys(data)) {
    typeData = { name: key, total: data[key].total, children: [] };

    // loops over the 'stages' for each of the outer keys
    for (const stage of Object.keys(data[key].stages)) {
      typeData.children.push({ name: stage, count: data[key].stages[stage] });
    }

    console.log('typeData pre-push: ', typeData);
    console.log('treeData pre-push: ', treeData);
    treeData.push(typeData);
    console.log('treeData post-push: ', treeData);
  }

 return treeData;
}

Although my function successfully converts the original object into the desired array format for amCharts, I seem to encounter an issue when pushing it into treeData as the CHILDREN values are lost. This discrepancy has been confirmed by logging the data in my react component, showing that the children array is empty.

I am trying to understand what causes the loss of children values when pushing the data into treeData?

Answer №1

The problem does not lie in adding the object to the treeData array, but rather in how the console logs of array objects are displayed in the VS Code terminal when they are nested inside another array. The code will show up correctly in the browser's console log.

Here is an example of what the VS Code terminal displays with two statements:

//Array inside an Object

console.log('Console Output in VS Code for  --->>', {name:"Something",values:[{id:"1"}]}); 

Output :

Console Output in VS Code for  --->> { name: 'Something', values: [ { id: '1' } ] }

//Array inside an Array

console.log('Console Output in VS Code for  --->>', [{name:"Something",values:[{id:"1"}]}]); 

Output:

Console Output in VS Code for  --->> [ { name: 'Something', values: [ [Object] ] } ]

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

Prevent scrolling while popup is open

I found a helpful tutorial online for creating a jQuery popup (). However, due to my limited understanding of jQuery, I'm having trouble getting it to meet my needs. The issues I'm facing are: I need to prevent the webpage from scrolling when ...

(Enhancing Angular) Capture HttpResponse errors and seamlessly proceed with the Observable

There's a dropdown text box with type-ahead search functionality. Valid item names prompt the expected list of items in the drop-down menu, while invalid entries trigger a 400 error response from the API. This error is caught by the HttpErrorIntercept ...

Why is my React app opening in Google Chrome instead of the API?

I have a link in my React app that is supposed to open a PDF in another page, but for some reason Google Chrome is redirecting me to the React application instead of opening the API endpoint that renders the PDF. The URL for the PDF is /api/file/:_id and m ...

Ensuring Unique CSS for Diverse Devices: A User-Agent Driven Approach

I am facing multiple challenges and working towards finding solutions. I have developed a webpage and now I want to redirect the link to the CSS file based on the user agent. `<script type="text/css" src="style.css"> </script>` However, inst ...

The AJAX request is not successful because it is encountering a ReferenceError due to attempting to assign a value to an

My attempt to trigger a modal using dynamic data from the database with an AJAX function is encountering issues. Upon clicking the button to open the modal, I encounter this error: ReferenceError: assignment to undeclared variable PostRPC in category.ph ...

Retrieve the corresponding value from an object received from express and display it on a jade template

I'm currently working on a solution to display the correct user information on a page when users navigate to "/users/:name". For example, I want to show "welcome user2" if user2 is logged in. My approach involves passing along the parameter from "/use ...

What's the reason that app.use(app.static(...)); isn't functioning properly?

As someone who is new to programming, I am currently exploring Javascript, node.js, and express. I came across a question regarding the usage of app.use(express.static(path.join(...))); versus app.use(app.static(path.join(...)));. const app = express(); co ...

Efficiently sanitizing a JavaScript object using the replace() method in JavaScript

I have a data object structured like this {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{&qu ...

Exploring the wonders of looping through arrays with JavaScript and jQuery

I am having trouble getting this function to work properly. My goal is to replace certain characters when a key is pressed. The code works fine using the variable `replace_list` instead of `replace_list["russian"]`, but I actually need different "replace ...

Having trouble displaying image using absolute path in Express

Currently, I am developing a NodeJS application and have encountered an issue with a div element that has a background-image set in an external CSS file. Surprisingly, the CSS file functions perfectly when tested independently, and the background image dis ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

Discovering the method for retrieving post parameters in Node.js

I am currently utilizing Node.js with Express and the httpAsyncClient library in Android. I have sent a request to Express using Post, including parameters. The request goes through successfully, but I am unable to retrieve the parameter in Post. I have ...

Blockage preventing text entry in a textarea

To enhance the basic formatting capabilities of a textarea, I implemented a solution where a div overlay with the same monospace font and position is used. This approach allows for displaying the text in the div with different colors and boldness. However ...

Why is my snapshot returning null, even though there are values in the Firebase Database?

I am currently facing an issue in my code related to the snapshot. Specifically, I am trying to retrieve the value of quantity from my Firebase Database. Here's a snapshot of my database: https://i.sstatic.net/qN6m4.jpg and https://i.sstatic.net/Gw ...

Alert users before visiting external websites

Is there a way to notify users about external pages without using popups like in the first example here: https://i.sstatic.net/5QJLu.png Instead of the unwanted code shown above, is there an alternative solution? Is there a different approach that can be ...

Is it possible for me to utilize this code for logging in through a dialog box?

Here is the code snippet I have on the client side: <p>Username:</p> <p><asp:TextBox ID="tbUsername" runat="server"></asp:TextBox></p> <p>Password:</p> <p><asp:TextBox ID="tbPassword" runat="server ...

Is there a way to eliminate duplicate elements from 2 arrays in Angular?

Imagine I have a scenario with two arrays: arr1 = ["Tom","Harry","Patrick"] arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"] Is it possible to eliminate the duplicate elements in these arrays? The desired output would be: arr2 = ["Miguel"," ...

The latest bug fix and update in Bootstrap 4.5.2 now includes an updated version of Popper.js. Make sure to use the

Hello fellow developers, I am currently working with npm bootstrap version 4.5.2 and above. However, I am facing an issue with the compatibility of @popperjs/core. If anyone can assist me in resolving the bootstrap.js error temporarily, specifically re ...

Using the Map Function in React JS to Dynamically Render Radio Buttons with Material-UI

Hey everyone, I'm looking for some assistance in replacing the old classic radio button with a new one using material-ui. I've been trying but haven't been successful so far. Any suggestions would be greatly appreciated. Thanks in advance. Y ...

I desire for both my title and navigation bar to share a common border-bottom

As I embark on my journey into the world of HTML and CSS, my knowledge is still limited. Despite trying various solutions from similar queries, none seem to resolve my specific issue. What I yearn for is to have both my title and navigation bar share the s ...