Determine the total number of nested objects within a JSON structure using Javascript

Consider the JSON structure below:

{
  "id": "foo",
  "list": [
    {
      "id": "A",
      "list": [
        {
          "id": "B",
          "list": [
            {
              "id": "C",
              "list": [
                {
                  "id": "D",
                  "list": []
                },
                {
                  "id": "E",
                  "list": []
                }
              ]
            },
            {
              "id": "F",
              "list": []
            },
            {
              "id": "G",
              "list": [
                {
                  "id": "H",
                  "list": []
                },
                {
                  "id": "I",
                  "list": []
                },
                {
                  "id": "J",
                  "list": []
                }
              ]
            }
          ]
        },
        {
          "id": "K",
          "list": []
        }
      ]
    },
    {
      "id": "L",
      "list": [
        {
          "id": "M",
          "list": []
        }
      ]
    },
    {
      "id": "N",
      "list": []
    },
    {
      "id": "O",
      "list": [
        {
          "id": "P",
          "list": [
            {
              "id": "Q",
              "list": []
            },
            {
              "id": "R",
              "list": []
            },
            {
              "id": "S",
              "list": []
            },
            {
              "id": "T",
              "list": [
                {
                  "id": "U",
                  "list": []
                }
              ]
            },
            {
              "id": "V",
              "list": [
                {
                  "id": "W",
                  "list": [
                    {
                      "id": "X",
                      "list": []
                    },
                    {
                      "id": "Y",
                      "list": []
                    },
                    {
                      "id": "Z",
                      "list": []
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

Your task is to count each child node and add this count as a property to each object.

For instance:

  • The "C" object has 2 child nodes, "D" and "E".
  • The "W" object has 3 child nodes, "X", "Y", and "Z".
  • The "V" object has 4 child nodes, including its own children ("W" and the three aforementioned).

To achieve this, each object should have a property, let's call it "allBelow", that contains the count of its child nodes. All objects need to be processed in this manner.

You may need to implement a recursive function for this task, as grouping nested child elements might require additional logic.

If you encounter any challenges with this, feel free to reach out for assistance.

Best regards,

Answer №1

var newObject = {"id":"foo","list":[{"id":"A","list":[{"id":"B","list":[{"id":"C","list":[{"id":"D","list":[]},{"id":"E","list":[]}]},{"id":"F","list":[]},{"id":"G","list":[{"id":"H","list":[]},{"id":"I","list":[]},{"id":"J","list":[]}]}]},{"id":"K","list":[]}]},{"id":"L","list":[{"id":"M","list":[]}]},{"id":"N","list":[]},{"id":"O","list":[{"id":"P","list":[{"id":"Q","list":[]},{"id":"R","list":[]},{"id":"S","list":[]},{"id":"T","list":[{"id":"U","list":[]}]},{"id":"V","list":[{"id":"W","list":[{"id":"X","list":[]},{"id":"Y","list":[]},{"id":"Z","list":[]}]}]}]}]}]};
 
function calculateItems(obj) {
  var count = obj.list.length;
  count += obj.list.reduce((a, e) => a + calculateItems(e), 0);
  obj.count = count; // assign the count after calculating the subobjects.
  return count; // return the calculated count to be used by parent objects
}
 
calculateItems(newObject);
 
console.log(newObject);

Answer №2

Here's a straightforward approach using Depth First Search (DFS):

function countTotalChildren(currentNode) {  
  const numChildren = currentNode.list.reduce((acc, node) => {
    return acc + countTotalChildren(node);
  }, 0)

  currentNode.allDescendants = numChildren;

  return numChildren + 1;
}

countTotalChildren(treeData);

https://jsfiddle.net/hyq37geL/

Answer №3

To solve this problem, I suggest using a depth-first search algorithm similar to the one below (Note: code is untested):

function performDFS(tree){
    var totalCount = tree.items.length;
    for(var j=0; j<totalCount; j++){
        totalCount += performDFS(tree.items[j]);
    }
    tree["total"] = totalCount;
    return totalCount;
}

Answer №4

If you're looking for a powerful algorithm, consider using a recursive function like the one below:

var data = {"id":"foo","list":[{"id":"A","list":[{"id":"B","list":[{"id":"C","list":[{"id":"D","list":[]},{"id":"E","list":[]}]},{"id":"F","list":[]},{"id":"G","list":[{"id":"H","list":[]},{"id":"I","list":[]},{"id":"J","list":[]}]}]},{"id":"K","list":[]}]},{"id":"L","list":[{"id":"M","list":[]}]},{"id":"N","list":[]},{"id":"O","list":[{"id":"P","list":[{"id":"Q","list":[]},{"id":"R","list":[]},{"id":"S","list":[]},{"id":"T","list":[{"id":"U","list":[]}]},{"id":"V","list":[{"id":"W","list":[{"id":"X","list":[]},{"id":"Y","list":[]},{"id":"Z","list":[]}]}]}]}]}]};

function addCount(node) {
  node.count = 0;
  for (var i = 0; i < node.list.length; i++) {
    var child = node.list[i];
    addCount(child);
    node.count += child.count + 1;
  }
}

addCount(data);
console.log(data)

This function recursively calls itself on each child node and calculates the count by including the number of grandchildren as well.

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 include extra properties during serialization in Jackson without altering the default POJO structure?

Using Jackson-ObjectMapper, I am generating JSON data based on my POJO. However, I want to include additional properties in the JSON without altering the POJO itself. Due to the POJO being a dependency in my project, modifications are not feasible. Is the ...

Tips for storing a JavaScript variable or logging it to a file

Currently working with node, I have a script that requests data from an API and formats it into JSON required for dynamo. Each day generates around 23000 records which I am trying to save on my hard drive. Could someone advise me on how to save the conte ...

There are two distinct varieties of object arrays

I recently encountered an issue while trying to sort my array of Star Wars episodes by episode ID. The problem emerged when comparing two arrays: one manually inputted in the code snippet labeled as "1" on the screenshot, and the other generated dynamicall ...

Arranging unrelated divs in alignment

http://codepen.io/anon/pen/Gxbfu <-- Here is the specific portion of the website that needs alignment. My goal is to have Onyx Design perfectly aligned with the right side of the navbar, or to have the navbar extend up to the end of "Onyx Design". The ...

Can a node.js file be exported with a class that includes IPC hooks?

[Node.js v8.10.0] To keep things simple, let's break down this example into three scripts: parent.js, first.js, and second.js parent.js: 'use strict'; const path = require('path'); const {fork} = require('child_process&apo ...

Is there a way to hide the row select option for individual rows in MUIDatatables without affecting the multiple row select options?

Is there a way to hide the checkbox in the header row that allows selection of all rows at once? I prefer to manually select multiple options by clicking on each individual row. Can the row select option be hidden? ...

Is there a way to populate an array with Twilio fax results and then successfully send them via Express?

Currently, I am working on integrating the Twilio API into our secured backend system before sending the data to our client app. This is being done to protect our API keys and for security purposes. We have successfully implemented fax sending and checkin ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

Is it possible to convert checkbox values from a form into a JSON format?

HTML snippet : <form class="form-horizontal" id="addpersons" style="padding:20px;"> <fieldset class="scheduler-border"> <!-- Form Title --> <legend class="scheduler-border">Information</legend> <!-- First Name input-- ...

Looking to retrieve country, state, city, and area based on inputting a pincode value using Node.js?

I'm currently working on a web project with nodeJs and ejs. I am looking for a solution that can automatically update the country, state, city, and area fields based on the input of a pin-code (zip-code). Are there any recommended packages in node js ...

Unable to activate Knockout data-bind using jQuery

I'm developing a plugin using jQuery and knockout.js. Currently, I have a scenario where I need to manipulate radio buttons with knockout data-bindings. However, I've encountered an issue when trying to uncheck a radio button by clicking another ...

What is the reason behind getElementsByClassName not functioning while getElementById is working perfectly?

The initial code snippet is not functioning correctly DN.onkeyup = DN.onkeypress = function(){ var div = document.getElementById("DN").value document.document.getElementsByClassName("options-parameters-input").style.fontSize = div; } #one{ heigh ...

Attempting to modify a JSON file within a React application

I recently obtained a JSON file named 'DealerList.json' which I managed to import into my app using the following code snippet: import DealerList from './json/DealerList' let tasks = DealerList; The tasks now store the JSON data and I ...

Breaking down a JSON array into individual rows in SQL

I need help parsing the 'custinfo' array into rows in my query instead of columns. The array can contain multiple values or none at all. DECLARE @json NVARCHAR(MAX) ='{ "customer": [ { "id": "123&quo ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Cypress OPENSSL_internal:NO_START_LINE error detected

Has anyone encountered this error before? I've already tried clearing the cypress cache and reinstalling it, but the error persists. I couldn't find a solution to resolve this issue. The version I am using is 6.5.0. Error: error:0900006e:PEM rou ...

Having trouble getting the JSONP request to render properly, encountering persistent errors

Need assistance with JSONP Rendering to HTML. The request is present in the source code, but I keep encountering errors on the foreach line. Any help would be greatly appreciated. <meta name="viewport" content="width=device-width, initial-scale=1"&g ...

Exploring the latest updates in MUI modern version

The MUI documentation suggests using a modern folder with components designed for modern browsers. Is there a way to configure webpack to automatically rewrite imports like import {Box} from "@mui/material" to use the modern version without manually changi ...

Make sure to wait for the fetch response before proceeding with the for loop in JavaScript using Node.js

I am facing an issue with my function that connects to a SOAP web service. The problem arises from the fact that the web service has limited connections available. When I use a for or foreach loop to search through an array of items in the web service, aro ...