Iteratively traverse the object to establish connections between parent and child elements

I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively

The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents in the hierarchy.

Personally, recursion isn't my strong suit, so maybe you can give it a shot :-) ... if you're up for experimenting with actual data, you can find it here

function eachRecursive(obj) {
    for (var k in obj) {
        if (typeof obj[k] == "object" && obj[k] !== null ) {
            eachRecursive(obj[k])
        }
        else {
            // perform action to add to codes
        }
    }
}

var o = {
    "1": {
        name: "hi 1",
        children: {
            "1.1": {
                name: "hi 1.1",
                children: {
                    "1.1.1": {
                        name: "hi 1.1.1",
                        children: {}
                    }
                }
            },
            "1.2": {
                name: "hi 1.2",
                children: {}
            }
        }
    },
    "2": {
        name: "hi 2",
        children: {
            "2.1": {
                name: "hi 2.1",
                children: {}
            }
        }
    }
}

var codes = {}
eachRecursive(o)
console.log(codes)
// Desired output.
//{
//    "1": {
//        "name":"hi 1",
//        "parents":[]
//    },
//    "2": {
//        "name": "hi 2",
//        "parents": []
//    },
//    "1.1": {
//        "name": "hi 1.1",
//        "parents": ["1"]
//    },
//    "1.1.1": {
//        "name": "hi 1.1.1",
//        "parents": ["1", "1.1"]
//    },
//    "1.2": {
//        "name": "hi 1.2",
//        "parents": ["1"]
//    },
//    "2.1": {
//        "name": "hi 2.1",
//        "parents": ["2"]
//    }
//}

Answer №1

One possible solution is shown below:

function iterateThroughObject(obj) {
    return (function recurse(result, obj, parents) {
        for (var key in obj || {}) {
            result[key] = { name: obj[key].name, parents: [...parents] };
            recurse(result, obj[key].children, parents.concat(key));
        }
        return result;
    })({}, obj, []);
}


var exampleObject = {
    "1": {
        name: "hi 1",
        children: {
            "1.1": {
                name: "hi 1.1",
                children: {
                    "1.1.1": {
                        name: "hi 1.1.1",
                        children: {}
                    }
                }
            },
            "1.2": {
                name: "hi 1.2",
                children: {}
            }
        }
    },
    "2": {
        name: "hi 2",
        children: {
            "2.1": {
                name: "hi 2.1",
                children: {}
            }
        }
    }
}

var resultCodes = iterateThroughObject(exampleObject);
console.log(resultCodes);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

When approaching this task, it's important to consider the process step by step as if you were doing it manually.

  1. If the item in question is an object: include the current node in the outcome, then recursively call the function with the expanded parents and the result.

  2. If it's not an object: simply add it to the result.

A demo has been set up for you here: https://jsfiddle.net/11e8e4af/

function eachRecursive(obj) {
  var parents = arguments[1] || [];
  var result = arguments[2] || {};
  for (var k in obj) {
    if (obj.hasOwnProperty(k) && typeof obj[k] == "object" && obj[k] !== null ) {
      result[k] = {name:obj[k].name, parents:parents.slice()};
      eachRecursive(obj[k].children, parents.concat(k), result);
    } else {
      result[k] = {name:obj[k].name, parents:parents.slice()};
    }
  }
  return result;
}

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

Styling of Bootstrap HTML element not appearing as expected

Recently, I've been trying out a new approach by embedding Bootstrap components in an iframe. However, despite loading the necessary stylesheet and scripts, the elements seem to be missing their styles. Can anyone shed some light on why this might be ...

Adding the "input-invalid" class to the input doesn't take effect until I click outside of the input field

When the zipcode field is updated, an ajax call is made. If there are no zipcodes available, I want to mark it as invalid by adding the "input-invalid" class. However, the red border validation only appears when clicking outside of the input field. Is ther ...

Trying to retrieve JSON data from an API in VueJS and successfully logging the results, but struggling to render the data on the page. (I

Having recently transitioned from React to VueJs, I encountered a problem where fetching data using axios.get returns a successful response in the console.log. However, when trying to iterate through the array with v-for, nothing is rendered. If you have a ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...

Adding existing tags to Select2 in Angular2 can be accomplished by following these steps:

HTML: <select data-placeholder="Skill List" style="width:100%;" class="chzn-select form-control" multiple="multiple"> <option *ngFor="#skill of allSkills" [ngValue]="skill">{{skill}} </option> </select> TS: allSkills = [& ...

Encountering a Node.js error when executing the JavaScript file

When I try to run my Node.js application using the command "node main.js" in the terminal, I encounter an error saying "Error: Cannot find module 'D:\nodeP\main.js'". This is confusing for me as I have set the environment variable path ...

The Express server automatically shuts down following the completion of 5 GET requests

The functionality of this code is as expected, however, after the fifth GET request, it successfully executes the backend operation (storing data in the database) but does not log anything on the server and there are no frontend changes (ReactJS). const ex ...

Configuring RingoJS to search for necessary modules within the node_modules folder

Currently, I am in the process of transitioning a service from nodejs to ringojs. My main hurdle involves the usage of require(). To illustrate, take a look at this snippet: var restify = require('restify'); The issue arises when RingoJS is una ...

The && symbol in JSONPath: combining conditions efficiently

Here is an example of JSON data taken from the tutorial: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", " ...

Retrieve particular JSON information on a single webpage by selecting an element on a separate page

My goal is to fetch specific information from a JSON file and display it on different HTML pages by clicking a button. I will achieve this using jQuery and plain JS. For the first HTML page, I want to show all products from the JSON in an element with id= ...

Is there a way to extract information from an external XML document and incorporate it into an HTML file?

I am attempting to extract information from an XML file that is not stored on my website's server. My goal is to utilize this data for various purposes, such as generating charts. One specific example involves using weather data from an XML file locat ...

An unexpected issue occurred during runtime, specifically a TypeError stating that the function posts.map is not

Currently, I am diving into the world of nextjs and decided to follow a tutorial on building a Reddit clone that I stumbled upon on Youtube. However, I encountered a persistent issue: posts.map is not a function I would appreciate any assistance you can o ...

How can the first character position be reached by moving the cursor using the jquery mask plugin?

I have done a lot of research but couldn't find the exact same question with a satisfactory answer. Therefore, I decided to ask a more specific question. I am using the Jquery mask plugin and I want my cursor to always be at the beginning of the textb ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

Issues with Twitter-Bootstrap Modal Functionality

After creating a modal dialogue: <a href="#myModal" role="button" class="btn" data-toggle="modal" id="LaunchDemo">Click here to launch the demo modal</a> <!-- Modal --> <div id="myModal" class="modal hide fade" tabindex="-1" role="di ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

AngularJS is throwing a $injector:modulerr error and I've exhausted all possible solutions

I recently started learning Angular and I've been following the tutorial on the official AngularJS website. Here's what I've tried so far: Installed angular-route and included the script below angular.min.js Utilized ngRoute in my mod ...

How come (23 == true) is incorrect but (!!23 == true) is correct? After all, there is === for exact comparisons

The question boils down to this: are both 23 and true truthy values? If so, shouldn't they be equal under the loose comparison operator ==? However, there is also the strict comparison operator === for cases where precise equality is required. UPDATE ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...