Exploring deeply nested arrays of objects until a specific condition is satisfied

My array is structured in a nested format as shown below.

const tree = {
        "id": 1,
        "name": "mainOrgName",
        "children": [
            {
                "id": 10,
                "name": "East Region",
                "children": [
                    {
                        "id": 11,
                        "name": "test east sub 1",
                        "children": [
                            {
                                "id": 12,
                                "name": "sub 22 sub 1",
                                "children": [
                                    {
                                        "id": 15,
                                        "name": "sub 333 of sub ",
                                        "children": [
                                            {
                                                "id": 16,
                                                "name": "sub 4444",
                                                "children": []
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            },
            {
                "id": 13,
                "name": "west region",
                "children": [
                    {
                        "id": 14,
                        "name": "test west sub 1",
                        "children": []
                    }
                ]
            }
        ]
    }

I am looking to go through the tree.children array to extract the id and name values from sub arrays and their children until there are no more children arrays. (Note: The children array may be empty or have multiple levels)

The expected result should look like this: Expected result

[
    {
        "name": "East Region",
        "value": 10,
        "selected": false
    },
    {
        "name": "test east sub 1",
        "value": 11,
        "selected": false
    },
    {
        "name": "sub 22 sub 1",
        "value": 12,
        "selected": false
    },
    {
        "name": "sub 333 of sub",
        "value": 15,
        "selected": false
    },
    {
        "name": "sub 4444",
        "value": 16,
        "selected": false
    },
    {
        "name": "west region",
        "value": 13,
        "selected": false
    },
    {
        "name": "test west sub 1",
        "value": 14,
        "selected": false
    }
]

I attempted the following code snippet:

const candidates = tree.children.map(org => ({name: org.name, value: org.id, selected: false}));

However, the output I received was different:

[
    {
        "name": "East Region",
        "value": 10,
        "selected": false
    },
    {
        "name": "west region",
        "value": 13,
        "selected": false
    }
]

I am striving to achieve the desired outcome but unsure how to implement a condition that continues traversing until the children are empty and pushes the required fields into the final array in the necessary format. I might need to utilize recursive/call back functions, but I'm uncertain about the implementation.

Your assistance in achieving the expected result would be greatly appreciated. Thank you.

Answer №1

Here's a JavaScript function to loop through a tree structure and extract specific values:

const tree = {
  "id": 1,
  "name": "mainOrgName",
  "children": [
  {
      "id": 10,
      "name": "East Region",
      "children": [{
        "id": 11,
        "name": "test east sub 1",
        "children": [{
          "id": 12,
          "name": "sub 22 sub 1",
          "children": [{
            "id": 15,
            "name": "sub 333 of sub ",
            "children": [{
              "id": 16,
              "name": "sub 4444",
              "children": []
            }]
          }]
        }]
      }]
    },
    {
      "id": 13,
      "name": "west region",
      "children": [{
        "id": 14,
        "name": "test west sub 1",
        "children": []
      }]
    }
  ]
}


let items = []

let result = retrieveValues(tree.children)
console.log(result)
function retrieveValues (arr) {
    for(let i = 0 ; i< arr.length ; i++){
    let obj = {}
    obj['name'] = arr[i]['name']
    obj['value'] = arr[i]['id']
    obj['selected'] = false
    items.push(obj)
    if(arr[i].children !== 0){
    retrieveValues(arr[i].children)
    }
  }
  
  return items
}

Answer №2

One efficient way to accomplish this task is by utilizing the concept of recursion

const tree = {
        "id": 1,
        "name": "mainOrgName",
        "children": [
            {
                "id": 10,
                "name": "East Region",
                "children": [
                    {
                        "id": 11,
                        "name": "test east sub 1",
                        "children": [
                            {
                                "id": 12,
                                "name": "sub 22 sub 1",
                                "children": [
                                    {
                                        "id": 15,
                                        "name": "sub 333 of sub ",
                                        "children": [
                                            {
                                                "id": 16,
                                                "name": "sub 4444",
                                                "children": []
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            },
            {
                "id": 13,
                "name": "west region",
                "children": [
                    {
                        "id": 14,
                        "name": "test west sub 1",
                        "children": []
                    }
                ]
            }
        ]
    }

function mapTree(children){
 let result =[]
 for(c of children){
   result.push({name: c.name, value: c.id, selected: false})
   result = result.concat(mapTree(c.children))
 }
 return result
}

console.log(mapTree(tree.children))

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

Accessing a specific element from an array of pointers

Recently in class, we covered pointers and heaps - how they function and their intricacies. I've been pondering the question of why it's not possible to use cout on a dereferenced pointer within an array. Take the code snippet below for instance: ...

The solution to enabling Type checking in this scenario is simple: Begin by addressing the issue of "Not assignable," followed by resolving any

After subscribing to an observable projected by a BehaviorSubject from a service, I encountered the following errors when trying to assign the subscribed value to a local variable: error TS2322: Type '{}' is not assignable to type 'DatosAdmi ...

What is the process for sending a POST request from a React app to a Node.js Express server?

I watched a tutorial video on resolving the CORS issue, which worked well for GET requests. However, I encountered an issue when attempting to send a POST request. Unfortunately, I do not have control over the third-party API and cannot make any changes to ...

Angular 2 Unit test issue: Unable to resolve parameters for 'RequestOptions' class

I am currently working on testing a simple component that has some dependencies. One of the requirements is to provide certain providers for the test. /* tslint:disable:no-unused-variable */ import { By } from '@angular/platform-browser&ap ...

Issues with Bootstrap Navigation Collapse Utilizing Data Attributes

I'm having trouble getting a Twitter Bootstrap 3 navbar to collapse using data attributes, as it is not expanding properly. Just to give some context, the project I am working on is an ASP.NET C# MVC project that runs on DNN (DotNetNuke) CMS. When I ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Learn how to implement RSS into your Next.js MDX Blog by integrating the `rss` module for Node JS. Discover the process of converting MDX content to HTML effortlessly

Having trouble converting MDX to HTML at the moment. This task is for Tailwind Blog You can find the complete code on Github here → https://github.com/tailwindlabs/blog.tailwindcss.com Below is the relevant code snippet: scripts/build-rss.js import fs ...

Issue with React: Children's state is altering the state of the parent component

Question : Why is it possible for a child component to change the state of its parent when each component has its own state? Below is the complete code for my app: import React, { Component } from 'react'; import { render } from 'react-do ...

What is the solution for resolving the JavaScript runtime error '0x800a1391 - 'require' is undefined'?

As a C# developer with limited web experience, I am currently diving into learning Typescript. However, I seem to be facing a roadblock in the form of an error message. 0x800a1391 - JavaScript runtime error: 'require' is undefined To provide so ...

What is the best way to include additional items in a list?

Trying to add a new element of an array to the list while updating one property (id) by making it 1 more than the length of the array has resulted in strange outputs. Each new object added causes all elements to have values of array.length + 1. Various at ...

How to change a time in HH:mm format to a Date object using JavaScript

I am facing a challenge with converting two time strings to Date objects and subtracting their values. The times I have are: 14:10 and 19:02 To perform the subtraction, I attempted to parse them using the following code: var res = date1 - date2; Howev ...

Issue with executing Jquery in PUG file: The $ sign is not being recognized despite jQuery being imported

I am encountering an issue where my jQuery code placed inside a pug template is not executing as expected. Despite including the jQuery file, when trying to run a jQuery function, I receive the error below: 40| P 41| ...

`Misconceptions in understanding AngularJS directives`

I am currently working on a new app that includes both a header and main view, utilizing directives. At first, I had the directive in its own file but decided to relocate it into app.js in order to resolve an issue. Throughout this process, I have experim ...

The password encryption method with "bcrypt" gives an undefined result

import bcrypt from 'bcrypt'; export default class Hash { static hashPassword (password: any): string { let hashedPassword: string; bcrypt.hash(password, 10, function(err, hash) { if (err) console.log(err); else { ha ...

What is the best way to determine the number of characters that will fit within the width of the document?

I am looking to create a JavaScript function using jQuery that can determine the number of characters that will fit in a single line within the browser window. While I am currently utilizing a monospace font for simplicity's sake, I would like to adap ...

Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when ...

HTML5 - Ajax - puzzling behavior that I am unable to comprehend

Need Help Clarifying My Issue: I currently have a Div with Page 1 content. Page 1 contains a button that transitions the div content to Page 2. Page 2 has a button that switches the div content back to Page 1. The Problem: If Page 1 is loaded first, t ...

Angular Pagination: Present a collection of pages formatted to the size of A4 paper

Currently, I am working on implementing pagination using NgbdPaginationBasic in my app.module.ts file. import { NgbdPaginationBasic } from './pagination-basic'; My goal is to create a series of A4 size pages with a visible Header and Footer onl ...

The returned type of intersected functions in Typescript does not match the inferred type

While attempting to extract the return type of an intersected request, I encountered a discrepancy between the return type and the inferred type. Check out the shortened URL for more details: https://tsplay.dev/mAxZZN export {} type Foo = (() => Promis ...

The issue with calling Ajax on button click inside a div container is that the jQuery dialog box is

Here is the code for my custom dialog box: $("#manageGroupShow").dialog({resizable: false, draggable: false, position:['center',150], title: "Manage Group", width:"50%", modal: true, show: { effect:"drop", duration:1000, direction:"up" }, hide: ...