"Implementing a feature in JavaScript that generates a child object within an array for every click event

On each button click, I aim to add an object as a child of the last existing object.

This is the code snippet I currently have:

const Myarray = [
    { id: 1, child:[] }
]

handleArrayDepth = (Myarray) => {
    Myarray.map(arrayitem => {
      let id = arrayitem.id;
      id++;
      arrayitem.child.push({
        id: id,
        child: []
      });
      if (id < 2) {
        this.handleArrayDepth(arrayitem.child);
      }
    });
};
console.log(Myarray);

The initial state of my array logs like this:

0:{
  id: 1,
  child: []
}

If the button is clicked twice, the output appears as follows:

0:{
  id: 1,
  child: [
    0:{
      id: 2,
      child: []
    },
    1:{
      id: 3,
      child: []
    }
  ]
}

However, what I am aiming for is the following structure:

0:{
  id: 1,
  child: [
    0:{
      id: 2,
      child: [
        0:{
          id: 3,
          child: []
        }
      ]
    }
  ]
}

I wish for this nesting to continue recursively/indefinitely with each click. I am currently struggling to find an efficient solution for this.

Answer №1

Several issues to address

  • Avoid using Array as a variable name
  • Avoid using map if you are not returning or mutating values
  • array.id is confusing since there is no variable named array in the original code

You can adjust your code by implementing recursive calls if the child length is greater than 0, otherwise push the value

const data = [{id: 1,child: []}]

handleDataDepth = (arr) => {
  arr.forEach(({id,child}) => {
    id++;
    if (child.length) {
      handleDataDepth(child);
    } else {
      child.push({id: id, child: [] });
    }
  });
};
handleDataDepth(data)
handleDataDepth(data)
console.log(data);

Answer №2

To simplify things, consider using a persistent variable that points to the last added object:

const collection = [{
  id: 1,
  children: []
}];
let latestParent = collection[0];

const updateCollectionDepth = () => {
  const { id, children } = latestParent;
  latestParent = { id: id + 1, children: [] };
  children.push(latestParent);
};

updateCollectionDepth();
updateCollectionDepth();
console.log(collection);

Answer №3

Have you thought about utilizing the closure function in this scenario?

let collection = [];

const handleArrayStructure = (function() {
    let identifier = 1;
    return function(array) {
        if (!array.length) {
            array.push({ id: identifier, children: [] });
        } else {
            identifier = array[0].id + 1;
            handleArrayStructure(array[0].children);
        }
    }
})();

function handleClickEvent() {
 const ulElement = document.getElementById("list");
 let listItem = document.createElement("li");
 handleArrayStructure(collection);
 listItem.innerHTML = JSON.stringify(collection);
 ulElement.appendChild(listItem);
}

document.getElementById("handler").addEventListener("click", handleClickEvent);
ul {
 list-style-type: none;
 margin: 0;
 padding: 0;
}

ul li {
 padding: 10px 10px;
 border: 1px solid #ccc;
 margin: 5px 0;
 border-radius: 4px;
}
<button id = "handler">Click Me!</button>
<ul id = "list">

</ul>

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

The bootpag event seems to trigger multiple times upon execution following an Ajax function call

I have integrated the bootpag jQuery pagination plugin from bootpag into my .NET/jQuery project. Within my project, there is a filtering menu that triggers an Ajax call to update the page with filtered or paginated data when a user selects a filtering opti ...

The module 'nodemailer' could not be located

Currently working with the Zapier Code tool, my goal is to send an email with Trello parameters. I've been using JavaScript encoding in combination with node.js for this task. However, every time I attempt to locate the 'nodemailer' module, ...

Angular Form Group without a name

Struggling to loop through my formgroups to identify which ones are valid and add the invalid ones to a new array. I can't seem to grab the name value for each formgroup. this.applicationFormArray = new FormGroup({ selectAppFormGroup:th ...

Creating a custom JavaScript clock based on stored database values

I am looking to create an analog clock using JavaScript. I have both working hours and off hours stored in a database. My goal is to display working hours in one color and off hours in another color on the clock. How can I achieve this? The database prov ...

What is the most effective method for nesting loops in NodeJS and Mocha?

Currently, I am attempting to create a loop within a loop in my NodeJS code, but I seem to be getting lost along the way. The results are not as expected - sometimes callbacks are triggered twice and so on. My approach involves using the async module. I wo ...

Docz: Utilizing Typescript definitions for props rendering beyond just interfaces

We are currently using Docz to document our type definitions. While it works well for interfaces, we've run into an issue where rendering anything other than interfaces as props in Docz components doesn't seem to display properly. I'm seeki ...

Using JQuery to attach a click event to a div element

My HTML code looks something like this: <div class="vmail vmail-bar normal-vmail-bar" id="pm_<?php echo $pm->to_id; ?>"> <div class="checkbox"><input type="checkbox" class="checkbox" /></div> ...

Efficient Ways to Utilize Global CSS in an Angular Project Without CLI

I am utilizing ASP.NET MVC as the server and Angular as the client application. Instead of a static index.html file, I have index.cshtml. The styles I am using are global styles rather than component-scoped. My query revolves around working with a bunch ...

I am trying to locate the XPath for the NG repeat element with the following code snippet: ng-repeat="thread in threads | orderBy:'-last_ts' | filter : globalSearch track by $index" Can you assist

<div ng-click="changeChatThread(thread, true)" class="item ui three column grid thread_item ng-scope active-thread" ng-class="{'active-thread' : selectedThread === thread.chat_id}" ng-repeat="thread in threads | orderBy:'-last_ts' | ...

Creating reactive data in a Vue.js 2 component

I'm currently learning Vue.js 2. I encountered an issue with my code while receiving dynamic data from a server (using Laravel 5.3). The problem arises when I attempt to declare the users array within the component instead of declaring it in the Vue() ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

Adding a dynamic text field when a checkbox is clicked: A step-by-step guide

To dynamically create a text field when a checkbox in the table is clicked, follow these steps. The table contains around 500 data entries, each with a checkbox for user selection of parameters. For example, if the "Testing 1" checkbox is clicked, the "Tes ...

After removing the timezone from the timestamp log, why is it now showing as one day behind?

Within my programming, I store a timestamp in the variable 'var timeStamp = finalData.obj.followers[0].timestp;', which currently outputs '2020-04-15T00:00:00.000Z.' To extract only the date and remove the time zone information, I util ...

Guide on changing the CSS of MUI parent components to set the display of buttons to 'block' in React

I'm facing a challenge with my modal design for mobile view. I need the buttons to display in a stacked format, one above the other, taking up the full width of the modal. I've been exploring ways to override the existing CSS within the component ...

Javascript/jQuery for enlarging and shrinking a div

Struggling with a function I'm implementing for a website. My goal is to move and expand a div upon button click, with the text on the button changing to "close". When the close button is clicked, the div should return to its original position. I&apo ...

How to effectively modify a worldwide array within a recursive function

I am currently enrolled in an algorithms MOOC and am working on a small program that calculates the number of inversions in an array A consisting of integers in arbitrary order. An inversion occurs when a pair (i,j) of indices in the array satisfy i<j a ...

Problems with Ajax functionality in CodePen

Currently working on the Wikipedia Viewer project for freeCodeCamp. I'm encountering an issue with the ajax function as nothing is being logged in the console upon click. The code snippet in question is provided below. Appreciate any help or insight o ...

Looking for a specific portion of a key-value pair

Currently, I am working on developing an application that will showcase parking tickets issued in New York City. The API that I am utilizing can be found at this link. My goal is to generate a graph illustrating the number of tickets handed out per month. ...

Insert picture from user's computer onto the canvas

I am currently developing a web application that allows users to create dynamic slideshows. However, I am facing an issue when trying to add images from the user's computer to the canvas. I have been using an input button to retrieve the file from the ...

Setting a CSS Variable with the Help of jQuery

I need help with changing the background color of a specific .div element when it is clicked on. I want the color to be a variable that can be changed by the user, and this change should occur when the document is ready. Currently, I am using a CSS variab ...