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

How can I insert an empty option following a selected value in a dropdown menu using jQuery?

How to use jQuery to insert a blank option after an existing option? I attempted to add a blank option, but it ended up at the top of the dropdown. I actually need one existing option followed by one blank option. For example: <option></option& ...

Conceal div elements and retain their status when the page is reloaded or switched

I currently have 3 div elements displayed on a webpage: header-div fixed_menu_div page_cont Each of these divs are styled with the following CSS properties: #header-div { top:0; left:0; display:inline; float:left; } #page_cont { mar ...

The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

Node.js refuses to launch - the dreaded error 404, signaling that it has mysteriously vanished

I am brand new to node.js, so please be patient with me as I learn. Currently, I am using the express framework and attempting to create a basic application that displays content as HTML. Below is the essentials of my app.js: var express = require(' ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Exploring the combination of Holder.js and Rails routes

What's the best way to integrate Holder.js into my Rails application? I'm running into issues where Rails is interpreting the parameters passed to the script as routes and returning 404 errors. Has anyone successfully implemented this before? ...

Having trouble getting a NodeJS sample app to start up because it can't locate the 'config' file?

I am currently delving into the world of Node.js and have been attempting to launch a sample application that I recently acquired from a git repository: https://github.com/madhums/node-express-mongoose-demo Despite diligently following all the provided i ...

Fresh ajax requests are not clearing the current data displayed in the JSP table

My ajax function retrieves data from a servlet and displays it in the page successfully. However, each time a new ajax call is made, the form appends the new data to the existing results instead of replacing them. I need to reset the current values stored ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

Creating an HTML string and then displaying its outer HTML in IE10 can be easily achieved. Just write the

My task is to write an HTML string to an element and then retrieve the resulting outer HTML from that element. This needs to be operational in IE10, latest versions of FF, Chrome, Safari, Android, iOS Safari but does not have to support any older browsers. ...

Peruse a spreadsheet for relevant information

I am currently facing an issue with a search bar that I implemented to filter through a table. However, for some reason, the filtering function does not seem to work on the tbody section of the table. The content in the tbody is generated dynamically usi ...

"Step-by-step guide on implementing a click event within a CellRenderer in Angular's Ag-Grid

paste your code hereI'm currently working on implementing edit and delete buttons within the same column for each row using Angular ag-Grid. To visually represent these buttons, I am utilizing icons. While I have successfully displayed the edit and de ...

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

Here's a unique version: "Strategies for effectively closing a modal when moving to a

I'm currently working with react-router-dom and material UI modal, and I am looking for a way to automatically hide the modal whenever the user navigates to another page. Here is my App component: const App = () => ( <BrowserRouter> &l ...

A div element springs forth into a new window and seamlessly transitions back to its original position with fresh content

Most of us are familiar with Gmail chat, where you can pop out the chat window into a new window with its content, and then pop it back in to its original position. However, I encountered an issue while working on replicating this functionality. While I w ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

Tips for making WebDriver pause until Sencha AJAX request finishes

While testing a page with Selenium WebDriver, I encountered an issue related to the Sencha JavaScript library being used on the underlying page. The problem arises when I input a value into a field and an AJAX call is made to validate that field. If the va ...