Guide on looping through deeply nested children within an object to accumulate a list of names

Within an object, there are numerous parent and child elements

var obj={
    name: 'one',
    child:{
        name: 'two',
        child:{
            name: 'three',
            child..
        }
    }
} 

foo(obj)                        

Create a function that produces the output ['one', 'two', 'three', ...]

Answer №1

It is recommended to implement a recursive function

var finalOutput = [];

function exploreDescendants(parentNode){
    if(parentNode.childElement){
        finalOutput.push(parentNode.name);
        exploreDescendants(parentNode.childElement);
    }
}

exploreDescendants(primaryObject);

https://jsfiddle.net/37pyj2ks/

Answer №2

One method to achieve this is by using recursion, where a function calls itself repeatedly until a certain condition is met. It essentially functions like a loop.

let object={
    name:'one',
    child:{
        name:'two',
        child:{
            name:'three'
        }
    }
} 


function printNames(object, arr) {
  if (!object) return arr;
  arr.push(object.name);
  return printNames(object.child, arr);
}

let results = printNames(object,[]);

Answer №3

Implement a while loop to go over each tier of your data structure until object.child is no longer available:

function retrieveData(object) {
  var information = []
  while (object) {
    information.push(object.name)
    object = object.child
  }
  return information
}

var object = {
  name: 'one',
  child: {
    name: 'two',
    child: {
      name: 'three'
    }
  }
}

console.log(retrieveData(object)) //=> ['one', 'two', 'three']

Answer №4

To achieve this, you can utilize a generator and curry both the object and the desired numbers.

function setObject(object) {
    return function* (n) {
        while (n--) {
            yield object.name;
            object = object.child;
        }
    }
}

var obj = { name: 'one', child: { name: 'two', child: { name: 'three', child: { name: 'four', child: { name: 'five' } } } } },
    getNumbers = setObject(obj);

console.log([...getNumbers(4)]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №5

After browsing through various answers, I found @stackoverfloweth's solution to be the most effective due to its simplicity and efficiency. However, I believe it can be further simplified while also ensuring that it includes the last level of the object:

var obj={
    name:'one',
    child:{
        name:'two',
        child:{
            name:'three'
        }
    }
} 

var res = [];
function search(obj){
    res.push(obj.name);
    !obj.child || search(obj.child);
}

search(obj);
console.log(res);

Answer №6

Below is a recursive function named getAllNames():

/**
 * Retrieves all `name` property values recursively
 *
 * @param o    an object
 * @param res  the resulting array
 * @returns {*|Array}
 */
function getAllNames(o, res) {
    var names = res || [];
    for (var k in o) {
        if (k === 'name') {
            names.push(o[k]);   // storing value of `name`
        } else if(k === 'child' && typeof o[k] === 'object') {
            getAllNames(o[k], names);  // handling nested `child` object
        }
    }
    return names;
}

var obj = {
    name:'one',
    child:{
        name:'two',
        child:{
            name:'three',
            child: {
                name: 'four',
                child: {
                    name: 'five'
                }  
            }
        }
    }
};

console.log(getAllNames(obj, []));

Answer №7

Here is a sample code snippet to achieve the desired functionality:

function recursiveFunction(arr, obj){
  if(obj){
    if(obj.name){
      arr.push(obj.name);
    }
    if(obj.child){
      return recursiveFunction(arr, obj.child);
    }
  }
  return arr;
}

function nonRecursiveFunction(arr, obj){
  while(obj){
    if(obj.name){
      arr.push(obj.name);
    }
    obj = obj.child;
  }
  return arr;
}

function mainFunction(obj){
  var array = [];
  
  // Using the recursive version
  return recursiveFunction(array, obj); 
  
  // Alternatively, use the non-recursive version
  // return nonRecursiveFunction(array, obj);
}

mainFunction(obj);

Answer №8

Several solutions involve checking for the absence of a child element when passing it as an argument in order to stop the recursion. This results in an additional function call that could potentially be eliminated.

function execute (object, array = []) {
    array.push(object.name);
    return object.child ? execute(object.child, array) : array;
}

Answer №9

Here is a code snippet that will generate an array like the following: ["one", "two", "three"]

var obj = {
  name: 'one',
  child: {
    name: 'two',
    child: {
      name: 'three'
    }
  }
}

var str = parser(obj);
var arr = str.substring(0, str.length - 1).split(";");

console.log(arr); // Output ["one", "two", "three"]

function parser(obj) {
  var text = obj.name + ";";
  if (obj.child) text += parser(obj.child);
  return text;
}

Answer №10

Give this a shot

let myString = generateString(myObj);
let myArray = myString.slice(0, myString.length - 1).split(",");

console.log(myArray);

function generateString(myObj) {
  let total = myObj.title + ",";
  if (myObj.sub !== null) total += generateString(myObj.sub);
  return total;
}

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

"Enhance your website with a dynamic Jssor slider featuring nested slides and vertical

Exploring the idea of merging the nested slider feature with a vertical thumbnail display. Reviewing the source code for examples image-gallery-with-vertical-thumbnail.source.html and nested-slider.source.html, I am wondering how to effectively combine t ...

Create a list that starts with a header determined by an object's attribute within an array

Currently in Vue, I am attempting to create a list based on a specific property within an object. The array being retrieved from the vuex store is structured as follows: const array = [ { name: "British title string" nationality: "British" }, { ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

Exploring JqueryUI tab navigation with the help of the <a> tag

I have come across several articles mentioning the possibility of navigating JqueryUI tabs using a button or anchor tag. Here is the method I am currently using: $("#vtabs").tabs(); $("#tabsinner").tabs(); $(".changeTab").click(function() { alert("as ...

Tips for saving user input from an HTML form into a database using PHP, and then transferring it to a variable in JavaScript

I've been working on a Wordpress project that involves two separate pages. The first page has a form for users to submit their name, which is then stored in a custom table in the database. After submitting the form, the user is redirected to another p ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

show a function written in JavaScript

I’m currently developing an API and looking to demonstrate a JavaScript code example for invoking this API. While writing a test function in JavaScript, I aim to execute and showcase the code for the JavaScript functions. However, my preference is to ha ...

Why won't AngularJS ng-click function properly?

I'm attempting to implement form validation using JavaScript. However, when I include the following line document.getElementById("one").setAttribute("ng-click", "insertData()"); inside the validateForm function, it doesn't work properly after ...

The issue with triggering button events in JavaScript

I've integrated a jquery modal popup for saving uploaded files related to a specific device. The modal appears, the cancel button functions correctly, but I am struggling to trigger the onclick event for the Save button... This is what I have impleme ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

Applying conditional logic within computed properties results in a failure to update

I have two different fiddles: Fiddle A and Fiddle B (both using Vuejs version 2.2.4) In my code, I have a computed property that can be changed programmatically by utilizing the get and set methods. Expectations for the Computed Property: If the def ...

Extract portions of the date into individual variables

My current project involves creating a front-end interface for data stored in a JSON database. The date information is saved in the following format: 12/31/16 I am trying to extract each of these values individually. Is there a method to assign variabl ...

The built-in functions of Wordpress are not able to be identified in the ajax PHP file

As a newcomer to Wordpress development, I am facing challenges with implementing ajax on my WordPress site. I am currently working on a plugin that requires the use of ajax. However, my php file (xxxecommerce.ajax.php) is not recognizing the built-in Word ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

In HTML, adjust column widths for multiple tables according to the widest column present in any of them

With Python, I am creating an HTML page that contains multiple tables with the same number of columns, all holding the same type of data. While the generated page is functional, I would like to improve readability by ensuring that all tables have the same ...

When updating the HTML content, JavaScript is outputting the code as text instead of running it

I am encountering an issue with adding the body content of a JSON file, which contains HTML code, to my existing HTML. Instead of executing the code, it appears as text within paragraph or header elements. I have searched through various discussions but ha ...

Why is it that the edit or delete button is not functioning when I attempt to click on the next page?

Having an issue with my script. It works fine for editing and deleting on the first page, but when I navigate to the next page, those functionalities stop working. Can anyone help me troubleshoot this problem? <script> $(function(){ $(&ap ...

How to access a global jquery function variable inside a foreach loop

Is there a way to modify the value of a global jQuery variable inside a foreach loop each time a new model item is encountered? I am looking to update the calendar with new dates but I need access to certain functions within the foreach loop to achieve thi ...

A guide on sharing an express.js response object with a different module

In my server.js file, I am attempting to pass an Express response object to a different module. Here is how I have implemented it: const room = require('../controller/rooms_controller') app.post('/rooms', function(req, res){ var na ...

Tips for customizing the border of an outlined TextField in MUI

Below is the current configuration of a TextField component: const styles = { resize: { fontSize: '50px', } } const textField = (props) => { const { classes } = props; return ( <TextField valu ...