The concept of matryoshka logic applied to data manipulation

"mainData"{
    entities:[]
},
"data2":{
    entities:[
        {
            name:"mainData":    //entites
        },
        {
            name:"mainData":    //entites
        },
        {
            name:"mainData":    //entites
        },
    ]
},
"data3":{
    entites:[
        {
            name:"data2":   //entites
        },
        {
            name:"data2":   //entites
        },
        {
            name:"data2":   //entites
        },
        {
            name:"data2":   //entites
        },]
}

I am looking to modify the data structure by adding a count to each object related to mainData. For example, in data2.entities there are 3 instances of mainData, so the count should be 3. Similarly, in data3.entities there are 4 data2s and since each data2 has 3 mainData inside it, the total count for data3 should be 12.

edit: How is the count for data3 12?

It is because there are 4 data2s in data3's entities, and each data2 has 3 mainData entries, resulting in a total count of 12 based on the mainData count.

The desired output structure would look like this:

"mainData"{
    entities:[]
},
"data2":{
count:3,
    entities:[
        {
            name:"mainData":    //entites
        },
        {
            name:"mainData":    //entites
        },
        {
            name:"mainData":    //entites
        },
    ]
},
"data3":{
count:12,
    entites:[
        {
            name:"data2":   //entites
        },
        {
            name:"data2":   //entites
        },
        {
            name:"data2":   //entites
        },
        {
            name:"data2":   //entites
        },]
}

Answer №1

If you need to calculate counts recursively:

const calculateCount = (data, name) => {
  if(name === "mainData") {
    return 1; // Base case: mainData has no nested entities, so count is 1
  } else {
    return data[name].entities.reduce((acc, entity) => (acc + calculateCount(data, entity.name)), 0);  // counts of nested entities
  }
}

// Calculate and add the count property to each data object
Object.keys(data).forEach(key => {
  data[key].count = calculateCount(data, key);
});

console.log(data);
<script>
  const data = {
    "mainData": {
      entities: []
    },
    "data2": {
      entities: [{
          name: "mainData"
        },
        {
          name: "mainData"
        },
        {
          name: "mainData"
        }
      ]
    },
    "data3": {
      entities: [{
          name: "data2"
        },
        {
          name: "data2"
        },
        {
          name: "data2"
        },
        {
          name: "data2"
        }
      ]
    }
  };
</script>

Answer №2

If you want to achieve a similar result, you can utilize the following code snippet:

const obj = {
  "mainEntity": {
    items: []
  },
  "dataSet2": {
    items: [{
        name: "mainData"
      },
      {
        name: "mainData"
      },
      {
        name: "mainData"
      },
    ]
  },
  "dataSubset3": {
    items: [{
        name: "dataSet2"
      },
      {
        name: "dataSet2"
      },
      {
        name: "dataSet2"
      },
      {
        name: "dataSet2"
      },
    ]
  }
};

const calculateCountFor = (property) => {
  return obj[property].count = obj[property].items.reduce((accumulator, currentItem) => {
    let count;
    if (obj[currentItem.name].items.length === 0) {
      count = 1;
    } else if (typeof obj[currentItem.name].count !== 'undefined') {
      count = obj[currentItem.name].count;
    } else {
      count = calculateCountFor(currentItem.name);
    }
    return accumulator + count;
  }, 0)
}

Object.keys(obj).forEach((key) => {
  calculateCountFor(key);
});

console.log(obj);

This code snippet iterates through each object property's items array and calculates the respective count based on the conditions provided. If an item has no count and an empty items array, the count is set to 1. If there is no count and the items array is not empty, the count for that object is calculated first.

Answer №3

A recursive method can be utilized to tally the nested elements.

To begin, develop a function that accepts an object and a key as inputs. This function will navigate through the object and calculate the occurrences of the key within the nested entities.

How does this function operate?

  1. If the object is an array, loop through each element and invoke the function recursively.

  2. If the object is an object with a property named name matching the key, increase the count.

  3. If the object is an object with a property named entities, call the function recursively on the entities property and return the total count.

Here's a sample technique;

let data = {
   "mainData": {
       entities: []
   },
   "data2": {
       entities: [
           {
               name: "mainData"
           },
           {
               name: "mainData"
           },
           {
               name: "mainData"
           }
       ]
   },
   "data3": {
       entities: [
           {
               name: "data2"
           },
           {
               name: "data2"
           },
           {
               name: "data2"
           },
           {
               name: "data2"
           }
       ]
   }
};

function countEntities(obj, key) {
   let count = 0;

   if (Array.isArray(obj)) {
       for (let i = 0; i < obj.length; i++) {
           count += countEntities(obj[i], key);
       }
   } else if (typeof obj === 'object') {
       if (obj.name === key) {
           count++;
       }
       if (obj.entities) {
           count += countEntities(obj.entities, key);
       }
   }

   return count;
}
data.data2.count = countEntities(data.data2.entities, "mainData");
data.data3.count = countEntities(data.data3.entities, "data2") * 3;

console.log(data);

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

What is the best way to utilize JSON.stringify for substituting all keys and values?

In my current project, I am exploring how to leverage the replacer function argument within JSON.Stringify in JavaScript to alter the word case (toUpper / toLower case). The challenge I am facing is that my JSON data is not simply key:value pairs; some val ...

Obtaining text from a select list using JQuery instead of retrieving the value

How can I retrieve the value from a select list using jQuery, as it seems to be returning the text within the options instead? Below is my simple code snippet: <select id="myselect"> <option selected="selected">All</option> <op ...

Steps for selectively extracting objects from an array containing nested objectsNeed a way to isolate specific objects

Currently, I am working on a project in JavaScript and have created an array called folders that holds multiple objects: folders = [folder1, folder2, folder3...] Each object within the array has various properties, one of which is docs that is an array o ...

Is there a way to display an XML listing recursively similar to the functionality of an ASP:MENU in the past?

I have been working on converting a previous asp:menu item to JavaScript. Here is the JavaScript code I have come up with: function GetMainMenu() { var html = ''; var finalHTML = ''; finalHTML += '<d ...

The Express.js server encounters a 404 error, causing it to panic and throw an exception before I can even address the issue

(Just so you know, I'm utilizing the Blizzard.js npm package in combination with Express.) I am currently working on a web application that allows users to search for statistics of specific video game characters (profiles created by players). Given t ...

What is the best way to determine if an item in an array is not empty?

Let's consider an array: arr = [{}, {}, {}, {}] If we want to determine the length of the array by counting only objects that contain at least one property, we can do this: [{}, {name: "Manchester United", odds: 3}, {}, {}] // 1 [{}, {name: "Liver ...

Linkyfy.js does not function correctly with each and not statements

Trying to incorporate a linkifying script on a website, which transforms URLs in text into clickable links. Utilizing the following solution: https://github.com/SoapBox/linkifyjs To make it operational (post-download), the following steps are required: & ...

What is causing the role="status" attribute to malfunction?

I'm having an issue with the role="status" attribute in my code. When using a screen reader, the paragraph text doesn't get read once it's appended to the body. index.html: <!DOCTYPE html> <html> <head> <title> ...

Tips for customizing the `src/app/layout.tsx` file in Next.js 13

I am looking to customize the layout for my /admin route and its child routes (including /admin/*). How can I modify the main layout only for the /admin/* routes? For example, I want the / and /profile routes to use the layout defined in src/app/layout.ts ...

Javascript Parameter

Each time I enter scroll(0,10,200,10); into my code, it seems to output the strings "xxpos" or "yypos" instead of the actual values. I attempted to remove the apostrophes around them, but unfortunately, that did not resolve the issue. scroll = function( ...

What is preventing the table from extending to the full 100% width?

Displayed above is an image showing an accordion on the left side and content within a table on the right side. I have a concern regarding the width of the content part (right side) as to why the table is not occupying 100% width while the heading at the ...

AngularJS grid designed to emulate the functionalities of a spreadsheet

I have been facing challenges with Angular while attempting to recreate a spreadsheet layout in HTML using ng-repeat. Despite extensive research, I have not found a solution. My goal is to display data in a table format as shown below: <table> & ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

Using jQuery and PHP to send a dynamic form through AJAX

I'm currently working on a pet registration form where users can add new pets. When a user clicks the "add pet" button, I use jQuery to clone the pet section of the form and give each cloned section an id like #pet-2, #pet-3, and so on. Although my ...

What's the advantage in using 2 functions instead of just utilizing one?

When I'm asking for help with my code, I make sure to include all of it in case there's a connection between the different functions. Recently, I received assistance to get one of my functions working properly. Specifically, I'm looking at t ...

The replace function fails to recognize Cyrillic characters when combined with the /b flag

Struggling with a persistent issue, I've noticed that my code works perfectly with Latin characters but fails to recognize Cyrillic characters when using jQuery. $('p').each(function() { var $this = $(this); $this.html($this.text().re ...

Webpack automatically prepends "auto/" to script tags in the compiled HTML file

I am currently setting up an application for coding, but I am facing a problem with webpack. Every time I build the application, webpack automatically adds "auto/file.js" to the script tags instead of just "file.js". I have checked all my webpack configura ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

Combining Summernote images with Node.js using Express.js

While there are numerous solutions available for handling the Summernote file-upload in PHP, I have struggled to find a satisfactory solution for Node.js. Here is My JavaScript: $(document).ready(function() { // $('#summernote').summernote( ...