Exploring and adding elements in a sophisticated array or object through recursive searching

After referring to this plunker https://plnkr.co/edit/CIGAA5BmiKU4hCMsOaIB?p=preview, I now require dynamic array operations.

[
{
    title: 'Menu 1',
    id :1,
    hide : true,
    children: [],
},
{
    title: 'Menu 2',
    hide : true,
    id :2,
    children: [{
        title: 'Sub Menu 2',
        hide : true,
        id :3,
        children: [{
            title: 'Sub Sub Menu 2',
            hide : true,
            id :4,
            children: [{
                title: 'Sub Sub Menu 2, Sibling 1',
                hide : true,
                id :6,
                children: []
            },
            {
                title: 'Sub Sub Sub Menu 2, Sibling 2',
                hide : true,
                id :12,
                children: []
            }]
        }]
    }]

},
{
    title: 'Menu 3',
    hide : true,
    id :14,
    children: []
}
]; 

My current task is to push children into the object with id 6 and update the entire object after each operation.

I am working with Angular 5.

The method I am using is as follows:

find(id, items,newData) {
  var i = 0, found;
  for (; i < items.length; i++) {
    if (items[i].id === id) {
      items[i].children=newData;
      return items;
} else if (_.isArray(items[i].children)) {
  found = this.find(id, items[i].children,newData);
  if (found) {
    return false;

      }
    }
  }
}

In this code, newData refers to the array that needs to be added, while items represent the main object that should be updated after an addition.

Please point out any mistakes in my approach. Additionally, if an element with id 3 has children with id 4, they should not be pushed under the same parent id.

All objects share a similar structure, where newData also contains children.

Answer №1

Implementing a recursive function in JavaScript

var arr = [{
  title: 'Menu 1',
  id: 1,
  hide: true,
  children: [],
}, {
  title: 'Menu 2',
  hide: true,
  id: 2,
  children: [{
    title: 'Sub Menu 2',
    hide: true,
    id: 3,
    children: [{
      title: 'Sub Sub Menu 2',
      hide: true,
      id: 4,
      children: [{
        title: 'Sub Sub Menu 2, Sibling 1',
        hide: true,
        id: 6,
        children: [{
          title: 'Sub Sub Menu 2, Sibling 1',
          hide: true,
          id: 7,
          children: []
        }]
      }, {
        title: 'Sub Sub Sub Menu 2, Sibling 2',
        hide: true,
        id: 12,
        children: []
      }]
    }]
  }]
}, {
  title: 'Menu 3',
  hide: true,
  id: 14,
  children: []
}];

// Defining a recursive function that modifies the array based on an ID
function findUpdate(array, id) {
  array.forEach(function(elem) {
    if (elem.id === id) {
      elem.children.push("updated")
    } else {
       if (Array.isArray(elem.children) && elem.children.length > 0) {
        findUpdate(elem.children, id)
      }
    }
  });

  console.log(arr)
}

console.log(findUpdate(arr, 12))

Answer №2

You are not returning the item as false, you need to either replace it or push.

var id = 6;
var items = [{
        title: 'Menu 1',
        id: 1,
        hide: true,
        children: [],
    },
    {
        title: 'Menu 2',
        hide: true,
        id: 2,
        children: [{
            title: 'Sub Menu 2',
            hide: true,
            id: 3,
            children: [{
                title: 'Sub Sub Menu 2',
                hide: true,
                id: 4,
                children: [{
                        title: 'Sub Sub Menu 2, Sibling 1',
                        hide: true,
                        id: 6,
                        children: [{
                            title: 'Sub Sub Menu 2, Sibling 1',
                            hide: true,
                            id: 7,
                            children: []
                        }]
                    },
                    {
                        title: 'Sub Sub Sub Menu 2, Sibling 2',
                        hide: true,
                        id: 12,
                        children: []
                    }
                ]
            }]
        }]

    },
    {
        title: 'Menu 3',
        hide: true,
        id: 14,
        children: []
    }
];
var newData = [{
    title: 'new Data'
}]
var find = (id, items, newData) => {
    var i = 0, found;
    for (; i < items.length; i++) {
        if (items[i].id === id) {
            items[i].children.push(newData); //change here if you want add in existing array
            return items;
        } else if (items[i].children.length != 0) {
            found = this.find(id, items[i].children, newData);
            if (found) {
                return items;
            }
        }
    }
    return items;
}

console.log(find(id, items, newData))

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

Discover the way to utilize the java enum toString() function in jQuery

In my Java Enum class called NciTaskType, I have defined two tasks: Pnd Review Woli and Osp Planning. public enum NciTaskType { PndReviewWoli, // 0 OspPlanning, // 1 ; @Override public String toString() { switch (this) ...

How can we display a fallback image if the Iframe is unable to load the resource at src in AngularJs?

In one of my JSP pages, I am utilizing an iframe and I want to set an external address as the src of this iframe. Typically, everything works fine. However, in cases where the external source is unavailable, I want to display a static image instead. I&apos ...

Addressing Overlap Issues in Angular 7 with NGXS and Firestore

Currently, I have a process in place where I retrieve data from Firestore and then update the state with it. Additionally, I make use of the NGXS Storage Plugin. While everything is functional, it does appear to be redundant. My approach involves a combi ...

Issues arise with the play method in Storybook and Jest when attempting to use the shouldHaveBeenCalled assertion on a

Here is a snippet of the component code: import { FC, ReactElement, useState, MouseEvent as ReactMouseEvent, ChangeEvent as ReactChangeEvent, } from 'react'; import { Stack, TablePagination } from '@mui/material'; export con ...

What purpose does the class serve in typescript?

This is a unique version of app.component.ts in the Angular Tour of Hero tutorial. import { Component } from '@angular/core'; export class Superhero{ name : string; id : number; } const SUPERHEROES : Superhero[] = [ {name : 'Wonder ...

What is the process by which JavaScript evaluates the closing parenthesis?

I'm currently working on a calculator project that involves evaluating expressions like (5+4). The approach I am taking is to pass the pressed buttons into an array and then create a parse tree based on the data in that array. One issue I'm faci ...

Effectiveness in identifying groups (?: => task(?:s+)?team COMPARED TO effort(s+)?group

Both of these formats suit my needs: E1=> work(?:\s+)?group E2=> work(\s+)?group I am looking to match either workgroup or work group, taking into account that the space could also be a line break (\s+)? My main concern is with th ...

At which location within the script should I insert the document.title in order to update the title every xx milliseconds?

I have been working on a script that refreshes certain #id's. Additionally, I would like to update the page title, which involves some flask/jinja2. I've attempted placing document.title = {% block title %} ({{online_num}}) Online Players {% en ...

Error encountered: Node Express Postgres application failing due to a syntax error in

Encountering an issue while attempting to pass variables to a PostgreSQL database: Error: syntax error at or near "," const rb = req.body; const sql= "insert into test1 (user, name, created) values (?, ?, CURRENT_TIMESTAMP);" poo ...

How can I use jQuery to access the parent node in an XML document?

I have been trying to extract the top-level 'label' attribute from the XML code below using jQuery, but I haven't had any luck so far. I have already converted it into a DOM object, but the results are not what I expected. Does anyone have a ...

What is preventing obj from being iterable?

When I try to compile this code, an error appears stating that the object is not iterable. Why is this happening? My goal is to determine the number of users currently online. let users = { Alan: { age: 27, online: false }, Jeff: { age ...

Express.js does not recognize the req.query value

Incorporating Stripe Checkout functionality into a MERN application has been the focus of my recent project. Upon successful payment by a customer, they are directed to a checkout success URL where the CheckoutSuccess page is displayed. Additionally, Stri ...

Vue/Vite vanilla setup encountering a 'Failed to fetch dynamically imported module' TypeError

We're currently working with a vanilla Vue/Vite setup and I'm encountering the error message TypeError: Failed to fetch dynamically imported module in Sentry logs. It appears that these errors coincide with new deployments to production, but I d ...

What is the best method for testing an AJAX application that fetches data from a live website?

I'm currently developing an AJAX application that retrieves data from a live website. Unfortunately, I am unable to replicate the entire application on my local environment at this time. In order to test whether the JavaScript code is functioning corr ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...

Set a dynamic Active Class on various divisions by utilizing their respective indexes

I have two divs with the same class. When I click on an anchor tag within one of the elements, I want to add a class to the corresponding position in the second div as well. Mirror: JSFiddle Here is the jQuery code snippet: $(document).on('click ...

An individual in a chat App's UserList experiencing issues with incorrect CSS values. Utilizing Jquery and socketio to troubleshoot the problem

Currently, I am testing a new feature in a chat application that includes displaying a user list for those who have joined the chat. The challenge is to change the color of a specific user's name on the list when they get disconnected or leave the cha ...

Steps for adjusting the matMenuTriggerFor area so it only triggers when hovering over the arrow

Hello there! I'm currently working on adjusting the trigger area for opening the next menu panel. Right now, the next menu panel opens whenever I hover over either the title or the arrow. However, my goal is to have the menu open only when I hover ove ...

Please enter a number to exclusively accept whole numbers with the use of the addEventListener method

My goal is to create an HTML input field that only allows entry of numbers between 1 and 999, with a maximum length of 3 characters. However, I am facing an issue with decimal numbers being accepted in the input. How can I restrict the input to only accept ...