Generating a nested JSON tree structure from arrays of objects through recursive iteration

My data structure is as follows:

{ projects: [
      { revisions: [
            { files: [] },
        ],
      }
  ],
  user: {}
}

To view the jsFiddle, click here: http://jsfiddle.net/winduptoy/EXdDy/

I am attempting to recursively generate a JSON hierarchy depicting an object's parents and their ids. Please check your console. Take a look at projects[0].revisions[0]._idTree, where the projects._id and revisions are displayed as a child of projects, just as expected. Now observe

projects[0].revisions[0].files[0]._idTree
, which shows projects.files as a sibling of projects.revisions, when files should actually be a child of projects.revisions. How can I resolve this issue?

Answer №1

To improve the functionality of recurseTree, consider making the following modifications:

function updateTree(tree, keyToUpdate, updatedId) {
    if(angular.element.isEmptyObject(tree)) {
        tree[keyToUpdate] = {_id: updatedId};
        return;
    } 

    var childNode = null; // retrieve current tree's child node
    for(var currentKey in tree) {
        if (currentKey != '_id') {
            childNode = tree[currentKey]; // locate a child node
            break;
        }
    }
    if (childNode) { // recursively process on child node
        recurseTree(childNode, keyToUpdate, updatedId);
    } else { // no child nodes found, update the tree directly
        tree[keyToUpdate] = {_id: updatedId};
    }
}

Answer №2

It appears that the correct option to utilize is:

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

Error in Java: Trying to cast an array of Objects to an array of Comparables is not allowed

Question Please develop a class called KeepSmallArray that utilizes an array to implement the KeepSmallInterface. Test your implementation using the TestKeepSmall program. The task involves discarding the two lowest scores from the assignment. Important ...

How to Target a Specific Element Using its Class with jQuery

Hey there! I'm currently working with the following snippet of HTML code: <li class="grey"> <div class="row"> <button id="test" style="width:50%;" class="btn btn-blue-white cartBtn">Add to Cart</button> </div ...

Tips for saving values created with JavaScript as an HTML file

I am looking to download an appended value as a HTML file. In my code, values are being appended from an external HTML file through an iframe. The code is functioning correctly and retrieving the right value. Now, I just need to download that appended valu ...

Manipulating Arrays in JavaScript: Adding and Removing Objects

let mapLayers = {}; //Create a new layer mapLayers.markers = new L.Group(); mapLayers.Name = t; layers.layer = mapLayers; An error is being thrown stating that layers.length is still 'undefined'. Can someone explain why this is happening? I ha ...

Parsing JSON using Newtonsoft library with HttpWebResponse

I've been trying to troubleshoot deserialization with Newtonsoft Json Converter by looking through various questions, but I can't seem to pinpoint the issue in my code. So, I'm reaching out here for some assistance. The error message from V ...

Exporting data from Excel in ASP.NET MVC

Looking for guidance here - I'm not well-versed in .NET or Javascript, so I'm struggling with a task. What's the simplest method to enable a user to download a JavaScript array of objects as an Excel spreadsheet? While exporting to CSV is st ...

Using React Router to send selected component to parent element

The content of App.js includes the following; render() { return ( <div className="App"> <Navbar /> </div> ) } Meanwhile, in Navbar.js class Navbar extends React.Component { render() { ret ...

Capture the response from an AJAX request and store it in a JavaScript variable

I've been struggling to find a solution for this issue for quite some time now without any success. Here's what I'm trying to accomplish: I need to retrieve an array from my PHP file so that I can utilize it in my JavaScript code. Example. ...

Having trouble establishing a new local Windows directory structure with Selenium

After following the guidelines provided here and here, I am striving to ensure that the directory where my results reports are stored is consistently available for each user. new File(sampleFolder).mkdir(); The sampleFolder path displayed in the Eclipse ...

Exploring the Connection with JSON-server

While creating a simulated API using json-server, I encountered an issue with passing a query. When utilizing _expand, I am able to display the parameters of a relationship, but it doesn't seem to work when the relationship is nested within a child. ...

Utilizing Spring JPA with JSON/JSONB Postgres columns for efficient data storage and

Despite searching for answers on this topic, I have not found a simple solution to my basic question. I am utilizing JPA CRUD Repository to store an entity. In my Postgres DB table, there is a column of type JSON and in my corresponding JPA Entity, the co ...

Changing the click event using jQuery

My JavaScript snippet is displaying a widget on my page, but the links it generates are causing some issues. The links look like this: <a href="#" onclick="somefunction()">Link</a> When these links are clicked, the browser jumps to the top of ...

Leveraging jquery datatable for displaying JSON data

Here is the JSON output I have: [{"param1":"value1","param2":"value2","param3":"value3"},{"param1":"value1","param2":"value2","param3":"value3"}] I have coded my AJAX request within a function that can be triggered by a button click: function callAjaxRe ...

Unusual behavior: Django app not triggering Ajax XHR onload function

I'm currently working on a Django app that features user posts, and I'm in the process of implementing a 'like' / voting system. Initially, I set up this functionality using complete page refreshes combined with a redirect after the vot ...

Identifying the HTML Hidden Attribute Using JavaScript Without Dependencies

As someone working in the analytics field, I often rely on CSS selectors to address various issues. Currently, I am faced with a task on a website where I need to determine whether a <p> element is hidden or visible. There are two possible scenarios: ...

The Power of Json, Ajax, and Javascript

Is there a way to regularly check for updates and update the relevant cell accordingly? I want the updated cell to flash and change color to red/green based on if it is a negative or positive numeric value. I will be using JQuery, Ajax, and JSON... Best ...

Implementing Mocking and Unit Testing with Node's Serialport Callbacks

Currently, I am developing a web interface for a third-party device that communicates over a serial port. An example of the code is provided below: const serialport = require("serialport"); const SerialPort = serialport.SerialPort; const sp = new SerialPo ...

How to Access Nested Arrays in ReactJS

As a ReactJS beginner, I've been making progress with my project. However, I've hit a roadblock that seems to be my final hurdle. Here's what I'm trying to achieve: TV Show - Simpsons Name: Bart Simpson, Gender: Male Name: Homer Simp ...

Acquire 2394 through the use of typescript

What could be causing this error? I have attempted different approaches, but the error persists without resolution Here is my code: function $sum(xor:string[]):string function $sum(xor:number[]):number { let xor_; if(xor instanceof String){ ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...