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

Using Jquery to send json data to a webserver via Ajax (API)

Currently, I am attempting to use AJAX to post data to a JSON file (API) on a server. As part of this process, I have implemented dragging functionality for two Kineticjs shapes on the stage. Upon stopping the drag action, my goal is to save the updated x ...

The selected jQuery plugin is not functioning properly within CodeIgniter framework

I recently downloaded the jQuery Chosen plugin to use the simple "multiselect" version on my website. I followed all the necessary steps and even copied and pasted the code into CodeIgniter. Despite my experience with jQuery, I am facing an issue where the ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

How to Invoke a TypeScript Function in Angular 2 Using jQuery

Using the Bootstrap-select dropdown in Angular 2 forms with jQuery, I am attempting to call a Typescript method called onDropDownChangeChange on the onchange event. However, it seems to not be functioning as expected. import { Component, OnInit, ViewChi ...

What steps can be taken to choose a particular class when multiple classes share the same name?

Imagine having a table layout like this: <table class="first-table" border="1" width="400px"> <tr> <td><?php echo $row_cond['title']; ?></td> <td><a class="more" href="#" onClick="slideup() ...

Process called gulp useref eliminates certain files from the pipeline

Is there a way to exclude the gulp.src file from output? I am aiming to bundle only JavaScript and output .js files, not HTML. The following blocks in base.html are utilized for bundling JavaScript with gulp-useref: <!-- build:js app.core.js --> &l ...

Troubleshooting issues with calculator operators in JavaScript for beginners

As a beginner in JavaScript, I've taken on the challenge of building a calculator to enhance my skills. However, I'm having trouble getting the operator buttons (specifically the plus and equal buttons) to function properly. Can someone please as ...

unable to reset contact form functionality

I need to implement a Contact Us form on my website. The form should clear the text fields after submission and display a Thank You message. Below is the HTML code: <div class="form"> <div id="sendmessage">Your message has been sent. Thank yo ...

Creating a definition for the use of sweet alerts within a service and incorporating them through

Implementing sweet alert for displaying alert messages in angularJS2/typescript. Due to the repetitive nature of this code in different parts of the application, a service was created. @Injectable() export class AlertMessageService { constructor(pr ...

What is the process for choosing a specific id from a JSON structure?

Is there a way to extract specific data from a JSON format within an Ionic project? What is the process for selecting the ID associated with particular data in a JSON format? And how can I retrieve and display the value linked to the selected product&apos ...

Utilizing PHP Variables in an External JavaScript: A Step-by-Step Guide

I am attempting to utilize an array generated in PHP within my external JavaScript. My PHP code retrieves images from a directory based on the user ID provided via URL and stores them in an array. I aim to use this array in JavaScript to create a photo sli ...

The 'palette' property is not found on the Type 'Theme' within the MUI Property

Having some trouble with MUI and TypeScript. I keep encountering this error message: Property 'palette' does not exist on type 'Theme'.ts(2339) Check out the code snippet below: const StyledTextField = styled(TextField)(({ theme }) = ...

Automatically navigate through form fields using jQuery when pasting data

Enhancing the form filling experience by allowing users to prepare a text file in advance and simply copy/paste it into the form for quick submission. Integration of a feature that automatically moves to the next input field when a tab or newline character ...

Discover how to retrieve full response data by entering text into a text field using Reactjs

I am encountering an issue while retrieving values from rendered data in a component that has already been displayed on the page. I want to input data into a text field and have it sent to the database, but using the runtime data from that specific field. ...

Identifying whether a Alphabet or a Digit has been Pressed - JavaScript

I understand that it is possible to detect if a key has been pressed and identify which key was pressed using JavaScript. In order to check if a key is down or pressed, jQuery can be utilized with ease: $( "#some id" ).keydown(function() or $( "#m" ). ...

Setting field names and values dynamically in MongoDB can be achieved by using variables to dynamically build the update query

I am working on a website where users can place ads, but since the ads can vary greatly in content, I need to be able to set the field name and field value based on user input. To achieve this, I am considering creating an array inside each document to sto ...

Is there a way to invoke a different function within a class from a callback function in an HTTP request?

Having an issue with my HTTP GET request function in the "CheckPrice" class. When trying to call another function within the class callback, it's showing as undefined. Any suggestions? const got = require("got") class PriceCheck { constructor() { ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

Activate the child for an update

Welcome! I am a newcomer to Angular and would greatly appreciate any assistance. The parent component of my picker has the ability to create various rules for each option. However, these rules are dynamic and can change frequently. I need to ensure that ...

Unable to execute redirect function in Next.js 14 application

I've been working on implementing basic authentication within a Next.js app, however I'm encountering issues with redirecting to the homepage from the auth.ts file. Below is a snippet of the code where I am implementing the loginForm: //loginForm ...