Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well.

The object y is an array consisting of key/value pairs, each containing two properties:

1. A unique string property called name. This value is identified by the children property, which is another array of objects similar to y.


    for (var i = 0; i < y.length; i++) {
      let objx = y[i];
      let name = objx["name"];
      let inner = objx["children"];
    
      for (var j = 0; j < inner.length; j++) {
        var z = inner[j]["name"];
        let h = inner[j]["children"];
        console.log(h);
      }
    
      // More nested loops on the 'h' object will follow.
    }
    

I am wondering if there could be a more streamlined method that can generate a new collection containing all the name string properties until each respective children property returns a count of zero.

Answer №1

const family = {
  name: 'parent',
  children: [
    {name: 'child1', children: []},
    {
      name: 'child2', children: [
        {name: 'grandChild1', children: []}
      ]
    },
  ]
};

const extractNames = family => [family.name, ...family.children.flatMap(extractNames)];
const allNames = extractNames(family);
console.log(allNames);

Answer №2

A possible solution is to implement a recursive function.

const
    retrieveNames = array => array.flatMap(({ name, children }) => [name, ...retrieveNames(children)]);
    

var array = [{ name: 'parent', children: [{ name: 'child1', children: [] }, { name: 'child2', children: [{ name: 'grandChild1', children: [] }] }] }];

console.log(retrieveNames(array));

Answer №3

This code demonstrates a simple example of recursion. The function recursively iterates over the data and calls itself with any children nodes that exist within the data structure.

var myData = [{
  name: 'bar',
  children: [{
    name: 'bar-1',
    children: [{
      name: 'bar-1-1'
    }]
  }, {
    name: 'bar-2',
    children: [{
      name: 'bar-2-1'
    }]
  }]
}]


function iterateOver(array, result) {
  array.forEach( function (data) {
    console.log(data.name)
    result.push(data.name)
    if (data.children) {
      return iterateOver(data.children, result)
    }
  })
  return result
}

console.log(iterateOver(myData, []))

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

I am attempting to trigger a mouseup event following a mousedown action

elements[0].onmousedown = function(){ console.log('screen clicked.'); triggerMouseUp(); }; I just need to incorporate a function in my code that simulates mouseup event, even when the user is still holding down the click button. e ...

When the first element of an array is undefined, Angular's ngFor will not render anything

We have an array called stringArray: var stringArray = new Array(); stringArray[1] = 'one'; In Angular, the ngFor directive displays nothing when stringArray[0] is undefined. How can this issue be resolved? ...

angularsjs state provider with multiple parameters

I am struggling to create a state provider that can handle multiple parameters. Is it possible to capture them as an object or array, or do I have to capture them as a string and then separate them? For example, this is my current provider: .state(' ...

Retrieve the HTML contents of a cell that contains a checkbox with the value of "jquery"

Here is an example of a table row: <tr> <td><input type='checkbox' name='post[]' value="1"></td> <td>08-Apr-2014</td> <td>injj team</td> <td>merchant.testyy.com</ ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

Custom font not displaying on Chromecast receiver app

I have followed the specified steps to incorporate a custom font into an html canvas text field. Interestingly, the font displays correctly when accessed on the Desktop Chrome browser, but on the Chromecast receiver application, the font fails to load. Wha ...

After converting from php/json, JavaScript produces a singular outcome

After running a PHP query and converting the result to JSON using json_encode, I noticed that when I try to print the results using echo, only one entry from the query is output in JSON format. My objective is to make this information usable in JavaScript ...

Choose a name to show when adding a new user in Firebase

Implementing authentication in my React app using Firebase has been successful for signing up and logging in. However, I have been facing challenges trying to include additional information during the sign-up process. I explored solutions provided on Stack ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

When querying parameters within a URL, you may encounter JavaScript (Node) errors

My current setup involves using Firebase Cloud Functions, but I have run into an issue. Whenever a parameter with a # symbol is received, it does not get recognized. For instance: http://example.net?id=123#456. When I check the logged id, only 123 is disp ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...

Stopping free jqgrid disabled toolbar buttons from reacting to mouse clicks can be achieved by implementing specific coding techniques that

When using Free jqgrid, toolbar disabled buttons may trigger click events on mouse clicks which can lead to invalid code execution. To demonstrate this, open the page below in Chrome and click on a disabled inline edit or pager button. A rectangle will app ...

Steps for creating a jQuery function that responds to changes in a text box value

Currently, I have a text box containing certain values and a submit button alongside a slider. When I click the submit button, the slider changes. However, I would like to achieve the functionality where instead of clicking the submit button, changing the ...

Steps to avoid TypeError: e.target.getAttribute is not a function

My goal is to make the inner code (result) function only when a Validity attribute is present. However, my target lacks said attribute, so I'm looking for a way to use an if statement to prevent the inner code from executing. How can I avoid the Type ...

Eliminate the Jquery Combobox

I've implemented the Jquery Combobox on my website /*! * Combobox Plugin for jQuery, version 0.5.0 * * Copyright 2012, Dell Sala * http://dellsala.com/ * https://github.com/dellsala/Combo-Box-jQuery-Plugin * Dual licensed under the MIT or GPL V ...

Store the active tab in AngularJS with Bootstrap to easily remember and display

After creating a basic AngularJS application with the Bootstrap directive, I noticed that some of my pages have tabs. The issue arises when I am on a tab other than the first one and click a link to navigate to another view. Upon returning (using either th ...

Guide on receiving application/csp-report as json in an express application utilizing bodyParser

I am currently working on creating a middleware that can receive CSP reports from browsers. Browsers send these reports with the Content-Type of application/csp-report, and the data is in JSON format. Right now, I'm using bodyParser.text to handle thi ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...