Manipulate a deeply nested JSON object in JavaScript by iterating through it and constructing a new data

Struggling to rearrange complex JSON data (data1) into a more organized format (data2). Progress has been slow.

data1 is created by scanning a parent directory (recipes) for html files.

data2 is the desired output structure using data1, where content within a folder should be represented as an array of objects rather than nested objects.

var data1 = {  
   "cake": {  
      "chocolate": {  
         "black-forest": {  
            "name": "Black Forest",
            "path": "recipes/cake/chocolate/black-forest.html"
         },
         "new-shortcake": {  
            "milk-chocolate-shortcake": {  
               "name": "Milk chocolate shortcake",
               "path": "recipes/cake/chocolate/shortcake/milk-chocolate-shortcake.html"
            },
            "dark-chocolate-shortcake": {  
               "name": "Dark chocolate shortcake",
               "path": "recipes/cake/chocolate/shortcake/dark-chocolate-shortcake.html"
            }
         }
      }
   },
   "pasta": {  
      "spaghetti": {  
         "aglio-olio": {  
            "name": "Spagehetti Aglio Olio",
            "path": "recipes/pasta/spaghetti/aglio-olio.html"
         },
         "carbonara": {  
            "name": "Carbonara",
            "path": "recipes/pasta/spaghetti/carbonara.html"
         }
      },
      "lasagna": {  
         "name": "Lasagna",
         "path": "recipes/pasta/lasagna.html"
      }
   }
}



var data2 = [
   {
      "name": "cake",
      "children": [
         {
            "name": "chocolate",
            "children": [
               {
                  "name": "Black Forest",
                  "path": "recipes/cake/chocolate/black-forest.html"
               },
               {
                  "name": "New Shortcake",
                  "children": [
                     {
                        "name": "Milk chocolate shortcake",
                        "path": "recipes/cake/chocolate/shortcake/milk-chocolate-shortcake.    html"
                     },
                     {
                        "name": "Dark chocolate shortcake",
                        "path": "recipes/cake/chocolate/shortcake/dark-chocolate-shortcake.    html"
                     }
                  ]
               }
            ]
         }
      ]
   },
   {
      "name": "pasta",
      "children": [
         {
            "name": "spaghetti",
            "children": [
               {
                  "name": "Spagehetti Aglio Olio",
                  "path": "recipes/pasta/spaghetti/aglio-olio.html"
               },
               {
                  "name": "Carbonara",
                  "path": "recipes/pasta/spaghetti/carbonara.html"
               }
            ]
         },
         {
            "name": "Lasagna",
            "path": "recipes/pasta/lasagna.html"
         }
      ]
   }
]

https://codepen.io/kyooriouskoala/pen/LLLXmG

Any assistance would be highly appreciated!

PS: Ultimate goal is to construct a menu utilizing the new data structure.

Answer №1

Is this the desired outcome you were looking for?

let result = [];
function parseTree(obj, temp){
for(let key in obj){

let folder = {};
if(obj[key] !== null && typeof obj[key] == 'object'){
  //console.log(key); 

  if(_.has(obj[key], "path")){
    folder.name = obj[key].name;
    folder.path = obj[key].path;
    folder.children = [];
  } else{
    folder.name = key;
    folder.children = obj[key];
  }

  result.push(folder); 
  parseTree(obj[key]);
}
} 

  return result;
} 

This function will structure your data as an associative object with the necessary values.

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 to give focus to a div in IE 8 after pressing the tab key, no jQuery required

We are facing a challenge with our datagrid where we have implemented navigation using the tab key. In IE 7 & 8, pressing the tab key shifts the focus away from the grid to the next element on the page. While in other browsers, we were able to prevent thi ...

Refreshing a page in MVC after making an Ajax call to the controller

In my controller, I have the following code: public async Task < ViewResult > Favourites(string ids) { // API call to fetch book data if (data != null) { var bookList = JsonConvert.DeserializeObject < Book[] > (data); ...

Looping through an array of JSON objects in Javascript results in finding instances, however, the process records them

Currently, I am executing a script inside a Pug template. The script commences by fetching an array of JSON objects from MongoDB. I then stringify the array (data) and proceed to loop through it in order to access each individual JSON object (doc). Subsequ ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...

Getting a 415 error when using InvokeApiAsync with StringContent in Monodroid/Xamarin.Android

Utilizing Xamarin Studio to create a Xamarin.Android application with Azure Mobile Service and .NET Backend custom managed API (WebApi 2). I have confirmed that my Mobile Service is functioning properly as I can see my app interacting with it in the logs. ...

Accessing JavaScript variables within Selenium

Currently utilizing Selenium Webdriver 2.0 to test an HTML page that incorporates an x.js file. Within x.js, the variable "price" is defined based on data entered from the HTML form and various Javascript calculations. In the HTML, the correct price valu ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...

Tips on extracting values from a JSON service

Hello, I am trying to retrieve the id and status from a service to log in. Below is the code that I have written. Please help me with getting the values. Thank you in advance. NSString *Username= txtUsername.text; NSString *Password=txtPassword.text; NS ...

The getBBox() method of SVG:g is returning an incorrect width value

Hey there, I've been attempting to determine the width of a <g> element and it consistently returns 509.5 pixels regardless of what I do. Initially, I assumed this was the actual size and not scaled. However, upon opening the SVG in Illustrato ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

Converting a CSV file to JSON only requires one line in the CSV file to create a corresponding JSON file

I'm facing an issue and I need your help! I am trying to convert a CSV file to JSON format where each line in the CSV file corresponds to one JSON file with the content of the CSV line. The name of the JSON file should be based on the ID of that line. ...

Error encountered while making an http get request for a node that returns JSON

I've been struggling with this issue for quite some time now. While I've come across similar problems on Stack Overflow, none of the suggested solutions seem to work for me. I keep encountering the following error message: undefined:1 SyntaxErro ...

store user settings in local storage

After writing some code with a link that toggles text visibility upon click, I now want to incorporate saving this state in web storage so that it persists upon page reload. As a beginner in JavaScript and HTML, this task has proven challenging for me. Th ...

Prevent users from adding or removing any letters

Exploring the ACE Editor integration with AngularJS (utilizing UI-Ace). I have a question. Is it possible to limit the user's actions to: Only allow entering a predefined character (for example, ;) Prevent deletion of any characters except for the p ...

Change the information displayed on buttons when clicked and provide options for users to navigate between different

In order to change the content when a button or number is clicked, you can utilize the buttons "1,2,3,4" or the Next and Prev buttons shown in the snippet. Both methods allow access to the same article. If you want to switch between articles using the Next ...

Implementation of Material UI Autocomplete feature with options consisting of an array of objects linking to both ID and label properties

Utilizing the Material UI Autocomplete component in my project has been a key feature. Referencing the official documentation, here are the available options: let options = [ { id: "507f191e810c19729de860ea", label: "London" }, { id: "u07f1u1e810c19 ...

What is the best way to combine a string with a variable in sass?

Is there a way to merge a string and a variable in Sass to form a variable name that is already present? $size: "sm"; $button-sm: 1rem; $buttom-md: 1.5rem; body { font-size: $button-#{$size}; } The desired output is: body { font-size: 1r ...

vuex: The decision between using $store.commit and directly calling the function

Recently, I discovered an interesting technique where store mutation functions can be passed into HTML events. Here's an example: //In the template <input name="the_field" :value="the_field" @input="updateField"/> // In the component methods ...