Find all elements in JavaScript that contain nested arrays

Here is an array that I have:

{
    "id": "parent",
    "code": "parent",
    "children": [
        {
            "id": "rtsp",
            "code": "rtsp",
            "children": [
                {
                    "id": "001",
                    "code": "cam30",
                    "source": "rtsp://192.168.43.29:8554/test",
                    "sourceFullScreen": "rtsp://192.168.43.29:8554/test"
                },
                {
                    "id": "002",
                    "code": "cam31",
                    "source": "rtsp://192.168.43.29:8554/test",
                    "sourceFullScreen": "rtsp://192.168.43.29:8554/test"
                },
                ...
                (more children elements here)
              ]
          },
        {... (other parent element)}
        {... (more parent elements)}
      ]
}

I am looking to retrieve the codes of all elements that have children.

My attempt at it was as follows:

jsonfile.readFile(file)
        .then(obj => {
            json = JSON.parse(JSON.stringify(obj));
            elements = getAllParents(json);
            console.log(elements);
            $('#parent').empty();
            $('#parent').append(firstChoice);
            $('#parent').append(elements);

        })
        .catch(error => console.error(error))

.
.
.


function getAllParents(json) {
    let childP = "";

    function read(json) {
        console.log(json);
        if (json.children !== undefined) {

            for (let i = 0; i < json.children.length; i++) {
                const element = json.children[i];
                childP += read(element);
                console.log(childP)
            }

           if(childP.includes(json.code) === false) childP += `<option value="` + json.code + `" >` + json.code + `</option>`;

        }
        return childP;
    }

    return read(json);

}

However, I am encountering an issue where my elements are being repeatedhttps://i.sstatic.net/DgArw.png

Can someone help me identify the error and suggest a resolution?

Answer №1

To determine if children are present, verify their existence and create a new array based on that.

function checkForChildren(obj) {
    if (!obj || typeof obj !== 'object' || !obj.children) return;
    const childrenArray = obj.children.reduce((res, child) => {
        if (child = checkForChildren(child)) res.push(child);
        return res;
    }, []);
    return { ...obj, children: childrenArray };                
}

var dataObject = { id: "parent", code: "parent", children: [{ id: "rtsp", code: "rtsp", children: [{ id: "001", code: "cam30", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "002", code: "cam31", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "003", code: "cam32", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "004", code: "cam10", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "005", code: "cam11", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "006", code: "cam12", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "007", code: "cam13", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "008", code: "cam14", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "009", code: "cam15", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "010", code: "cam16", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "011", code: "cam17", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "012", code: "cam18", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "013", code: "cam19", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "014", code: "cam9", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "015", code: "cam7", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "016", code: "cam8", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "017", code: "cam5", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }, { id: "018", code: "cam6", source: "rtsp://192.168.43.29:8554/test", sourceFullScreen: "rtsp://192.168.43.29:8554/test" }] }, { id: "test", code: "test", children: [{ id: "cam100", code: "cam100", source: "cam100", sourceFullScreen: "cam100" }, { id: "zone-a", code: "zone-a", children: [{ id: "cam100a", code: "cam100a", source: "cam100a", sourceFullScreen: "cam100a" }] }, { id: "cam101", code: "cam101", source: "changed", sourceFullScreen: "changed" }, { id: "cam102", code: "cam102", source: "cam102", sourceFullScreen: "cam102" }, { id: "cam103", code: "cam103", source: "cam102", sourceFullScreen: "cam102" }, { id: "cam105", code: "cam105", source: "cam105", sourceFullScreen: "cam105" }] }] },
    finalResult = checkForChildren(dataObject);

console.log(finalResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Creating a radio button along with a submit button that redirects to a different local HTML file

Can someone please help with this code? I'm trying to redirect to the value of each radio button when it's clicked. Any guidance or JavaScript code would be greatly appreciated. Thank you. I've tried multiple solutions but none of them seem ...

The concept of Theme.breakpoints does not exist in MUI React, there is

I keep running into the same error where theme.breakpoints is undefined when I try to use theme.breakpoints.up in my code. The versions of the dependencies I am currently using are: "@emotion/react": "^11.9.0", "@emotion/styled&quo ...

Setting a date in Angular Material 2 without closing the mdMenu

I am trying to interact with Material 2's menu. Is there a way to select a menu item without closing the menu popup? Check out this link for more information. ...

Javascript collapsible panel that is initially expanded

I found this code example here and decided to implement a collapsible panel using css/html/javascript: function toggleCollapsibleSectionWithAnimation() { this.classList.toggle("collapsible-active"); var buttonId = this.id; var sectionId = buttonId ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

I attempted to retrieve a card using two nested maps, but unfortunately the data did not display as expected

I attempted to add data in Gotocart.jsx using a nested map, but I'm having trouble getting anything to display on the page. Below is the code for Gotocart.jsx: import React from 'react' import { useState } from 'react' import { da ...

"The interconnection between NetBeans, jQuery, and AJAX is

My issue is with a Netbeans 7.4 (also tried 7.3) project involving PHP and JavaScript where breakpoints do not work in jQuery ajax loaded pages that contain included JavaScript. I have no problem with PHP or top-level JavaScript, but for example: In index ...

Steps for aligning the upper rectangular text in the center of the larger rectangular border

https://i.stack.imgur.com/7yr5V.png I was aware of a particular element in html that had text positioned in the upper left corner, but my knowledge didn't go beyond that. Should I be adjusting the translation on both the X and Y axes based on the par ...

VueJS 3 custom Checkbox fails to update UI upon clicking

I'm attempting to implement a customized checkbox using Vue 3 and the composition API based on this example. However, despite confirming through devtools that all my props and bound data are successfully passed from the parent component to the child c ...

Display all information associated with the class that matches the clicked ID

Can anyone help me with a Jquery question? I am trying to display all data with the same class when I click on it. I have created a list of clickable items. When I click on an item, the corresponding data should be shown. However, the code I wrote is not ...

What is preventing this brief code from functioning properly? I am trying to extract a value from an input field and add it to a div element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jque ...

Adjust the contents of an HTTP POST request body (post parameter) upon activation of the specified POST request

Is there a way to intercept and modify an HTTP Post Request using jQuery or JavaScript before sending it? If so, how can this be achieved? Thank you. ...

Change the price directly without having to click on the text field

Our Magento marketplace site is currently utilizing the code below for updating prices. However, we are looking to make the price field editable without requiring a click on the textfield. This means that users should be able to edit the price directly wi ...

Optimal methods for sending Redux state to components

Currently, I am collaborating on a React + Redux project alongside other developers, and we are at an impasse regarding the best practice for passing state and actions throughout our components. My strategy involves creating a 'container' or &ap ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Display specific content according to the hash in the URL

I have a website with a page (/categories.html) that contains around 50 p elements: <p id='BCI'>Blue_colored_items</p> <p id='RCI'>Red_colored_items</p> ... What I want is for the page to only display: Blue_co ...

Struggling to make the switch operational

I'm struggling to make this switch statement work. I want to have multiple conditions like in an if-else statement, but I can't seem to figure out how to add more than two conditions. function spriteAI1() { var posX = c2Sprite.p ...

How can I show the remaining paragraph text upon clicking a button in a responsive manner using CSS and JavaScript?

I want to add a nice animation effect to the height of my text when a button is clicked. I've managed to achieve this by setting a height: 30px with overflow: hidden initially, and then toggling a class with height: 300px. However, I'm facing an ...

ThreeJS: Is CSG the missing wrapper?

I have been utilizing ThreeCSG.js independently to generate various shapes, but I am encountering errors when attempting to create certain shapes: Maximum call stack exceeded. It appears that the repository is not being updated, so I experimented with the ...