Calculating the total sum of child node values across all parent nodes

[
    {
        "level_key":"lvl1",
        "level_value":"Code1",
        "values":[
            {
                "name":"a",
                "value":0
            },
            {
                "name":"b",
                "value":0
            }
        ],
        "children":[
            {
                "level_key":"lvl2",
                "level_value":"Type1",
                "values":[
                    {
                        "name":"a",
                        "value":0
                    },
                    {
                        "name":"b",
                        "value":0
                    }
                ],
                "children":[
                    {
                        "level_key":"lvl3",
                        "level_value":"Desc1",
                        "values":[
                            {
                                "name":"a",
                                "value":0
                            },
                            {
                                "name":"b",
                                "value":0
                            }
                        ],
                        "children":[
                            {
                                "level_key":"lvl4",
                                "level_value":"Check1",
                                "values":[
                                    {
                                        "name":"a",
                                        "value":2
                                    },
                                    {
                                        "name":"b",
                                        "value":3
                                    }
                                ],
                                "children":[]
                            },
                            {
                                "level_key":"lvl4",
                                "level_value":"Check2",
                                "values":[
                                    {
                                        "name":"a",
                                        "value":4
                                    },
                                    {
                                        "name":"b",
                                        "value":5
                                    }
                                ],
                                "children":[]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

I've attempted to tackle the issue by repeatedly looping through different levels, but this approach is flawed due to the varying number of levels. Here is the initial input:

[ { "level_key":"lvl1", "level_value":"Code1", "values":[ { "name":"a", "value":0 }, { "name":"b", "value":0 } ], "children":[ { "level_key":"lvl2", "level_value":"Type1", "values":[ { "name":"a", "value":0 }, { "name":"b", "value":0 } ], "children":[ { "level_key":"lvl3", "level_value":"Desc1", "values":[ { "name":"a", "value":0 }, { "name":"b", "value":0 } ], "children":[ { "level_key":"lvl4", "level_value":"Check1", "values":[ { "name":"a", "value":2 }, { "name":"b", "value":3 } ], "children":[] }, { "level_key":"lvl4", "level_value":"Check2", "values":[ { "name":"a", "value":4 }, { "name":"b", "value":5 } ], "children":[] } ] } ] } ] } ] I have attempted a brute force method where I iterated through the maximum possible number of levels, which is not ideal as the number of levels can vary. The expected output should be:

[
    {
        "level_key":"lvl1",
        "level_value":"Code1",
        "values":[
            {
                "name":"a",
                "value":6
            },
            {
                "name":"b",
                "value":8
            }
        ],
        "children":[
            {
                "level_key":"lvl2",
                "level_value":"Type1",
                "values":[
                    {
                        "name":"a",
                        "value":6
                    },
                    {
                        "name":"b",
                        "value":8
                    }
                ],
                "children":[
                    {
                        "level_key":"lvl3",
                        "level_value":"Desc1",
                        "values":[
                            {
                                "name":"a",
                                "value":6
                            },
                            {
                                "name":"b",
                                "value":8
                            }
                        ],
                        "children":[
                            {
                                "level_key":"lvl4",
                                "level_value":"Check1",
                                "values":[
                                    {
                                        "name":"a",
                                        "value":2
                                    },
                                    {
                                        "name":"b",
                                        "value":3
                                    }
                                ],
                                "children":[]
                            },
                            {
                                "level_key":"lvl4",
                                "level_value":"Check2",
                                "values":[
                                    {
                                        "name":"a",
                                        "value":4
                                    },
                                    {
                                        "name":"b",
                                        "value":5
                                    }
                                ],
                                "children":[]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Answer №1

It seems like you're organizing your levels as children within the main level, which can be confusing. A more efficient approach would be to implement a reduce function along with a recursive function to map out the items in a better way.

function calculateTotal (key, children) {
  if (children.length > 0) {
    return children.reduce((acc, value) => {
      // Locate the item with the specified key
      const foundItem = value.values.find((item) => item.name === key));
      
      // Add its value to the accumulator or zero if not found
      return acc + (foundItem ? foundItem.value : 0);
    }, 0); // Starting object value is 0
  }

  // Return 0 if there are no children
  return 0;
}

function processChildValues(items) {
  return items.map((item) => {
    if (item.children.length > 0) {
      // Recursively calculate and apply child items
      const processedChildren = processChildValues(item.children);
      children = processedChildren;
    } else {
      children = [];
    }

    const values = [];
    
    // Calculate values based on children's totals
    item.values.forEach((valueItem) => {
      const name = valueItem.name;
      const value = calculateTotal(name, children);
      
      // Create new value items with calculated values
      values.push({ name, value });
    });

    // Update values for parent calculations
    item.values = values;
    item.children = children;
    return item;
  });
}

This code snippet serves as a guide on using recursion to traverse nested arrays efficiently in your scenario. It hasn't been tested yet, but should help you get started.

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

`How can I implement auto-scrolling for a container using React?`

I'm currently working on a React code useEffect(()=>{ if(!currentTitle && value && message){ setCurrentTitle(value) } if(currentTitle && value && message){ setPreviousChats(pre ...

display PHP JSON information using jQuery AJAX

I'm completely new to this subject. I have a Json result that looks like the following : { "span": " 1", "numcard": "12", "chan": " Yes", "idle": "Yes", "level": "idle ", "call": "No ", "name": "" } My goal is to ...

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...

Understanding which page is being rendered through _app.js in React/Next.js is crucial for seamless navigation and

Currently, I am working on rendering my web navigation and footer on my _app.js file. My goal is to dynamically adjust the style of the navigation and footer based on the specific page being accessed. Initially, I considered placing the navigation and foot ...

Store transient information in JSON

Struggling with incorporating JSON into my project! I'm aiming to track user changes and save them to a SQL database using AJAX and PHP later on. Initially, I want to structure all user modifications in a JSON object before finalizing the process. I& ...

Interacting with a form in Node.js does not print out the form values to the

I am just starting to learn about node.js and I'm attempting to create a form that includes fields for 'name' and 'department'. However, when I submit the form, both 'name' and 'department' are showing up as &ap ...

Select Items Based on Filtering Arrays

Within the JSON format below, there exists a state in addition to a checkbox state that signifies the selection of categories. initialData = [ { store_name: 'Shop 1', women: false, men: false, kids: true}, { store_name: 'Shop ...

Programme for Server Login

After creating my own server, I attempted to implement a login feature to restrict access to its files. Unfortunately, using Javascript for this task proved to be insecure as usernames and passwords could easily be viewed in the source code: <form name ...

The Axios onDownloadProgress function on the GET method is only triggered one time, and the setTimeout within the callback is never executed

I'm currently working on displaying a progress bar while fetching data from the backend API. However, I've encountered a couple of issues that I'm struggling to resolve. Firstly, the progress bar jumps from 0 to 100 without showing any actua ...

Issue with Updating Array Rows in React Insertion and Deletion Operations

Issue with updating array in parent component. Having trouble updating the array in the Parent component when adding a new row. The values get updated when selecting dropdown and textfield, but the array does not reflect the changes. Tried using useReduce ...

Manipulating data in a C# application using JSON

I am currently developing a desktop application for managing requests and responses. So far, I have successfully implemented GET requests, but now I need assistance in understanding how to handle JSON requests and responses. Once I can parse the JSON dat ...

Encase the message in a mat expansion panel if it exceeds a certain length

I am working on wrapping an XML message in a mat-expansion-panel to ensure it flows down if the content is too long, instead of extending beyond the panel boundaries. <mat-expansion-panel class="panel"> <pre>{{pretty(message.content ...

Retrieve and modify the various elements belonging to a specific category

I'm currently developing a chrome extension and I need to access all elements of this specific type: https://i.stack.imgur.com/sDZSI.png I attempted the following but was unable to modify the CSS properties of these elements: const nodeList = documen ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

Having trouble with transitions in CSS using React.js?

I am facing an issue with a CSS property transition that is set to height 3s, but it's not working as expected. The context is within a React.js application. Despite my attempts, there is no smooth transition effect on the height when triggered. Her ...

Clearing the text field after submitting the content

I am trying to remove the content of a text field after adding an option into a select list. Here is an example of the HTML code: <select size="15" style="width:230px" style="text-align:right" id="theaterSelectControl"> <option>111</opt ...

Is it unwise to rely on Sequelize for validating objects that are not stored in a database?

Currently, I am utilizing Sequelize as my ORM and find the powerful built-in model validation to be quite impressive. I am contemplating leveraging Sequelize as a schema validator in specific scenarios where there would not be any actual database writes. E ...

Tips for incorporating validation/restrictions into react-datepicker

I've been working on implementing restriction and validation in a react-datepicker component. I'm utilizing redux-form for validation and normalization purposes. Issue: I've noticed that neither the normalizing function nor the validation f ...

Using Entity Framework Core with FOR JSON AUTO can simplify the process of serial

Is there a way to use FOR JSON AUTO in SQL Server with EF Core? I have views in my database that I need to query, filter with a WHERE clause, and return the data as JSON using the FOR JSON AUTO clause. I'm looking to achieve something like this: str ...

"detail": "An error occurred while parsing the JSON - Expected a ',' delimiter:

I'm facing an issue with JSON while trying to pass a POST request. The error message I am receiving is: "detail": "JSON parse error - Expecting ',' delimiter: line 3 column 34 (char 36)" Here is the POST request that I made: { "song": {"ar ...