Guide on iterating through an array of objects a specified number of times to ensure it loops through all child arrays within the objects, if they exist

How can I iterate through an array of objects a certain number of times to access all the child arrays within each object and retrieve their IDs in order?

let data = [{
  "id": "1",
  "child": [
    {
      "id": "12",
      "child": [
        {
          "id": "123",
          "child": [
           {
            "id": "1234"
           }
        }
      ]
    },
    {
      "id": "2",
      "child": [
        {
          "id": "22"
        }
      ]
    },
    {
      "id": "3"
    },
    {
      "id": "4",
      "child": [
        {

          "id": "42",
          "child": [
            {

              "id": "43"
            }
        }
      ]
    }
  ]
}]

Expected Output

[1,12,123,1234,2,22,3,4,42,43]

This is my attempt at solving it, but I am unable to find a working logic:

result.reduce((pv, cv) => {
  console.log(cv)

  let temp = cv
  let arr = []
  if(temp.hasOwnProperty("split")){
    arr = temp.split
    pv.push(temp.id)
    // I need help with iterating through 'arr' here!
  }
  return pv
}, [])

If anyone has any logical steps or ideas to share, I would greatly appreciate it!

Answer №1

To tackle this issue, you should implement a recursive function that utilizes a persistent variable to reference the array. Using .reduce is not suitable in this scenario, and your test involving temp.split does not align with the properties under consideration - namely, id and child. It is crucial to unconditionally push the ID (outside the if statement) and recursively call the function on the child array if it exists.

const input=[{id:"1",child:[{id:"12",child:[{id:"123",child:[{id:"1234"}]}]},{id:"2",child:[{id:"22"}]},{id:"3"},{id:"4",child:[{id:"42",child:[{id:"43"}]}]}];

const getAllChildIds = (arr, ids = []) => {
  for (const { id, child } of arr) {
    ids.push(Number(id));
    if (child) getAllChildIds(child, ids);
  }
  return ids;
};
console.log(getAllChildIds(input));

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

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

Error in compiled.php on line 7772: Laravel throwing a RuntimeException when sending HTTP requests from Angular

Hey there, I've been encountering an error intermittently while using Angular $http methods with a Laravel API. Can someone please explain what this error means and suggest potential solutions? I've shared the error log on CodePen for easier refe ...

"Implementing form validation and AJAX submission for seamless user interaction

I am seeking a solution to validate my form using ajax and then insert it into the database also utilizing ajax. Although, with the current code, validation messages are displayed, it still performs the insertion. The issue I am encountering seems to be ...

Swap out the <a> tag for an <input type="button"> element that includes a "download" property

I have been working on a simple canvas-to-image exporter. You can find it here. Currently, it only works with the following code: <a id="download" download="CanvasDemo.png">Download as image</a> However, I would like to use something like th ...

Error sending an email through the EmailJS backend JavaScript file

I am in the process of creating a route for my backend JavaScript Express server called server.js that will trigger an email to be sent to my Gmail account using EmailJS. When I attempt to use the following code: const SMTPClient = require("emailjs& ...

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

Avoiding Ajax overload/server collapse in an Arduino/ESP8266 setting

I've recently been delving into Arduino programming to host an HTML/CSS/JavaScript webpage on an Adafruit HUZZAH ESP8266 breakout board. Please pardon any unconventional methods I may be using. My approach involves utilizing Ajax to update pressure g ...

Issue with AngularJS: Dynamically generated tab does not become active or selected

Exploring an AngularJS code snippet that generates tabs upon clicking the new button. However, there's an issue where the newly created tab doesn't become active or selected automatically after creation. It seems like the one before the last tab ...

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

Turn off sticky sidebar feature for mobile-friendly layout

I have encountered an issue with my script that I need assistance with. I am trying to disable this script for responsive or mobile view, but despite trying various methods, it is not functioning as expected. <script type="text/javascript"> $(func ...

Tips on finding the right parent object by utilizing the information stored in the nested array

I have a collection of objects structured as follows: var items = [ { itemId: 0, itemQuantity: 10, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "Black" } ] }, { itemId: 1, itemQuantity: ...

Managing the rendering of charts in Angular with Directives

I'm in the process of creating an admin page with multiple elements, each revealing more information when clicked - specifically, a high chart graph. However, I've encountered a challenge with the rendering of these charts using a directive. Curr ...

Unveiling the secrets of interacting with localstorage in react.js

I'm currently facing an issue with a component that retrieves data from an array stored in local storage. Although the initial data is fetched when the page loads, I am unsure how to update it when changes are made in local storage. import React, {Co ...

Issue with function execution within useEffect() not being triggered

I am facing an issue where two functions in my component are not being called every time it renders, despite my efforts. Placing these functions in the dependency array causes an infinite loop. Can anyone identify why they are not executing? function Por ...

Find the item that has a specific value in its sub-property

Information Models: public class Header{ public int Identifier; public int value; public bool anotherValue; public List<Trailer> trailers; } public class Trailer{ public int ID; public Language MyLanguage; public string ...

What is the best way to generate an array containing multiple arrays, each filled with dynamic Divs?

I have the following code that displays a Div when the user clicks on the Add button. For example, if the user clicks the Add button 5 times, then 5 will be displayed with the same controls/inputs under default. html <div ng-repeat="st in stu"> ...

elevate the div with a floating effect

My goal is to create a chat feature for users that will only be visible for a limited time period. I was thinking of using PHP and timestamp to achieve this functionality, but I also want to make the chat visually disappear by having the message div float ...

Tips on retrieving the ul list value dynamically using jQuery when it changes

I have a list of countries with their dial codes and country codes. I need to find out which country is currently selected and retrieve its data-country-code using jQuery. Can anyone provide guidance on how to accomplish this? <ul class="country-list ...

What is causing this code to break when using ajax's `data` parameter?

I'm relatively new to JavaScript, and I've been working on some code that seems to be properly formatted. However, whenever I add the data elements, it breaks the code. I've checked the jQuery documentation and as far as I can tell, I'm ...

A guide on utilizing webpack devServer proxy within a create react app

Currently, I am in the process of developing a new application with create-react-app and I am looking to incorporate some proxies into my code. In the past, I utilized webpack's devServer for this purpose. module.exports = { ... devServer: { ...