Most effective method for generating numerous branching arrays in JavaScript

When creating shorthand objects, I find that there are too many indents with other arrays and objects inside. I am building a question form that branches out to new sets of questions based on the previous one answered. Do you have any suggestions on how I should design this code?

Answer №1

Organize your data using a tree structure as demonstrated below:

var
node0 = {/*data*/},
node1 = {/*data*/},
...
node3234 = {/*data*/}
node0.children = [node1, node2, node3]
node1.children = [node11, node12, node13]
...
node3234.children = []

If you need to reuse subtrees, simply do this:

node2321 = node1234,

Avoid creating cycles like the example below:

node2222 = node2,
...
node1111.children = [node1]

Answer №2

A different approach for a more concise solution:

const data = {
  '': {},
  '1': {},
  '1.1': {},
  ..
  '3.2.3.4': {}
};

for (let key in data) {
  data[key].children = [];
}

for (let key in data) {
  if (key !== '') {
    let hierarchyArray = key.split('.');
    let level = hierarchyArray.pop();
    let parentKey = hierarchyArray.join('.');
    
    if (parentKey in data) {
      data[parentKey].children.push({level: +level, key: key});
    } else {
      console.log('Pending subtree: ' + key);
    }
  }
}

for (let key in data) {
  data[key].children = data[key].children
    .sort((a, b) => a.level - b.level)
    .map(x => data[x.key]);
}
// The tree structure is now stored in data['']

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

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

Attempting to transform text into symbols

I'm puzzled by this situation where an infinite loop is created and I can't figure out the reason behind it. Interestingly, the loop doesn't occur when the push command is not used. #words = ["Apple", "Banana", "Cherry", "Date", "Elderberry ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

Troubleshooting async/await issues in certain IDEs

I've been experimenting with aysnc and await in my project. While it worked perfectly in FiddleJS, I encountered an error when trying to implement it in my IDE (PHPSTORM 2017): async function test(url){ ^^^^^^^^ SyntaxError: Unexpected token f ...

Creating dynamic images in JavaScript by assigning URL paths from string variables

Currently, I am utilizing JavaScript to parse through an XML file. One interesting aspect of the XML is that it contains URLs which link to images like this one: http://localhost/pic.jpg Throughout the parsing process, I am storing each URL as a string va ...

I'm wondering if it's possible to fork an npm library in package.json and automatically trigger its build process upon installation

I am currently facing an issue with a npm dependency, such as ngx-infinite-scroll, that I am trying to fork for bug fixes. I want to include my modified version as a dependency in my application. Here is an example of how I have included it in my package.j ...

Problems arise when using AngularJS' .run function after navigating to a different page

I have encountered an issue with ngRoute while navigating between pages in my web application. The main login page is called index.html, and the routing is controlled by the main js file. However, I face a problem when trying to use a .run block on a speci ...

Utilizing jQuery to explore a JSON object from Google Books

I successfully retrieved a list of books using the Google Books API. I stored the JSON object in localStorage and then converted it back into an object: var books = JSON.parse(localStorage.books); Now, I am looking to retrieve information for a specific ...

Allow images to be uploaded using the browser-policy package in Meteor

Can anyone help me figure out how to use Sir Trevor JS in Meteor for uploading images without encountering this error message? When attempting to load the image 'blob:http%3A//localhost%3A3000/a28ef7dc-ee51-4290-9941-6b8fc317e685', I am receivin ...

Creating distinct identifiers for CSS JQ models within a PHP loop

Can anyone assist me in assigning unique identifiers to each model created by the loop? I am currently looping through a custom post type to generate content based on existing posts. I would like to display full content in pop-up modals when "read more" i ...

What steps should I follow to include a message in the custom form validation rule in my React application?

I'm currently developing a chat application using React 18 and Firebase 9. For cleaner form validation, I have integrated the Simple Body Validator. Within the Register form, there's an input field of type file for uploading user avatars. The ...

initiating a submission upon the occurrence of an onchange event on an input field of type "file"

I have encountered an issue while trying to submit a form using the onchange event of an input element with type file. The problem is that it submits an empty form even when a file has been chosen. Here is the code snippet: var form = document.createElem ...

The custom component in ngx-formly remains unchanged after updating the model

I am utilizing custom component fields in my project. Initially, everything works smoothly until I attempt to replace the model with a different one. Unfortunately, the component for each field does not get updated with the new value. No events seem to ...

Photo captured by camera is not stored in photo gallery

I am currently working on a basic image upload form that allows users to take photos using their phone camera and upload them. However, I have noticed that the pictures taken this way are not being saved to the gallery. Is there something missing in the H ...

Is it necessary to include `load` events if scripts are placed at the bottom of the body?

Is it necessary to enclose code in the following: window.addEventListener('load', () => {}) If your scripts are already loaded at the end of the body tag? Wouldn't this ensure that the DOM has been fully loaded, rendering a load event li ...

Error encountered in C when trying to initialize a 2D array leading to Segmentation fault

I'm encountering an issue when trying to declare and initialize a 2D array in a headers file. I declared the array like this: int **arr; then allocated memory for it and initialized all elements with zeros. However, I keep getting a segmentation fault ...

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

JavaScript on Event

My task is to develop a landing page that requires users to input a promotion code in order to proceed. There are three possible scenarios: the user enters the correct code and is redirected to another page, the user enters the wrong code and is taken to a ...

Dealing with nested JSON objects in NodeJS may result in the return of [Object

I'm trying to extract nested JSON objects from a JSON array, but instead of getting the actual objects, I'm seeing [Object]. Here's an example of my JSON structure: var json = { "root_id": [ { "child-id1": { "name": "nam ...

Initiate modal from sub-component

Right now, I am developing a vue application with a structure that closely resembles the following: <div class="characters"> <Character v-for="character in this.charactersToSearch" :key="character.id" :name="cha ...