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

The command "bin" is not identified as an internal or external command in this npm script

I'm new to using node/npm and encountering an issue when attempting to start an npm script. Every time I try to execute a simple script like the one below, I get the error message "bin is not recognized as an internal or external command." I have suc ...

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

Utilize filters on a dataset to display specific information

Front-end: const [filters, setFilters] = useState({ type: "", country:"", }); const onChangeFilterType = e => { const workingObject = {...filters}; workingObject.type = e.target.value; setFilters(workingObject); }; ...

The functionality of sending POST parameters with a Volley JsonObjectRequest has been disabled

I'm attempting to send POST parameters in a Volley JsonObjectRequest. Initially, I had success by passing a JSONObject containing the parameters in the constructor of the JsonObjectRequest as advised in the official documentation. However, suddenly it ...

A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations. For example, when removing properties from objects, I usually use the following function: function cloneOmit ...

Searching for nested divs with the same class name in jQuery can be achieved by using the

Need assistance in locating all divs with a specific class name. Some divs may have nested divs with the parent div's class name. Take this scenario for example: <div class="myForm"> <div class ="myDiv"> <div class ="myDiv"> ...

What is the best way to merge strings and JMESPath queries in order to construct a webhook payload?

I'm currently exploring the use of Cloud Custodian webhooks to generate tagged events in Datadog using the Datadog API. The code snippet below is almost functional, however, the tag for account_id is not being created in Datadog. When examining the b ...

Ways to merge several getServerSideProps functions

Within my project, I have two important pages: index.js and other.js. In index.js, there exists a crucial method known as getServerSideProps: export async function getServerSideProps(context) { //code here } The challenge arises when I realize that I ...

Executing a JavaScript function when an element is clicked using inline

Is it possible to write the code below in a single line? <a href="#" onClick="function(){ //do something; return false;};return false;"></a> As an alternative to: <a href="#" onClick="doSomething(); return false;"></a> functio ...

Reveal the administrator's details exclusively when the associated radio button is chosen

Managing administrators for a post can be done through an editing page with corresponding radio buttons. Each radio button is linked to a different administrator, and selecting one populates the form fields with that admin's details. The issue arises ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

JavaScript event handler for dynamic button click

I am creating a unique button dynamically for each row in a table to handle deletions. I am assigning the id of the button with the key of the row, allowing me to retrieve it later when clicked. Since all buttons share the same function, passing the specif ...

jQuery scrollTop(0) leading to unusual scrolling patterns

Every time I click on a button, a modal window appears with a fading effect: $('.display-all-comments').fadeIn(300); $('.display-all-comments').scrollTop(0); If I remove the scrollTop(0), the scrolling works as usual. To better illust ...

Implementing JavaScript Functions to Trigger Control Key and Plus/Minus Events

In my project, I have a unique set of selectors called A+. By clicking on the A+ button, it has been programmed to initiate the control plus event. Similarly, within the same interface, I also have an A- button that activates the control minus event when ...

What is the procedure for submitting all checkbox values through Google Apps Script?

My web app created using Google Apps Script can generate a custom table of data for users to select for calculations. I use Google Sheets to populate the table with values and checkboxes, but note that the table size may vary depending on the user. <fo ...

Different methods exist for hashing a JSON's key-value pairs when the value type and number of pairs are not known

Upon receiving a JSON in string format from the database, all that is known is that it follows a key-value structure. The number of pairs in the JSON string and the type of value (String or Object) are not predetermined. Below are some examples of JSON St ...

Preventing mouse clicks on checkboxes and triggering events using JavaScript - a complete guide

We have a Table grid with multiple columns, one of which is a Select Box (CheckBox). The expected behavior is that when a row is clicked, the respective CheckBox should get checked, and clicking on the CheckBox itself should update it. I tried implementin ...

The jsx file is not being parsed by Webpack

In my current project, I am working with a JSX file that contains React code. import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; ...

Every single data attribute is unique for each element

Hello! I'm currently working on creating a sorting system for pictures, documents, and videos. Each div contains data-extension attributes, so my plan is to filter out all attributes that are jpg, gif, or png and make them visible while hiding the oth ...

"Learn the trick to replace the Ctrl + N shortcut in Firefox and initiate an AJAX request

Note: The answer provided by Juan Mendes has been selected as the best answer for my situation due to its usefulness. AxGryndr also offered valuable information, so I recommend reading both answers as they are beneficial in different scenarios. Thank you t ...