Creating dynamic nested objects using Javascript

In my quest to create serialized objects within the main object, I have come up with the concept of a solar system as an example of nesting. This allows me to access a variable by referencing it like this:

universe.system1.planet4.x

The hierarchy is universe > system > planet, and so on.

I am facing a dilemma with generating nested structures. Currently, I can only successfully implement one level of nesting.

setInterval(onTimerTick, 1000); 
function onTimerTick() {

var entityCount = 4;
for (i = 1; i < entityCount; i++){
console.log('system' + i)
universe['planet' + i] = [entityCount, entityCount, entityCount, entityCount];  
}//entitycounts in object are placeholder for more data
console.log(universe);
}

var universe = {
}

Output

Object {
system0: [5, 5, 5, 5],
system1: [5, 5, 5, 5],
system2: [5, 5, 5, 5],
system3: [5, 5, 5, 5]
}

Every attempt at adding further nesting layers results in failure.

Answer №1

Could this possibly be the solution?

In order to achieve this result, you will need to implement X nested loops, where X represents the desired number of nested levels.

const nbSystem = 5;
const nbPlanetPerSystem = 3;

// Establish the base structure
const universe = {};

// Generating systems
for (let i = 0; i < nbSystem; i += 1) {
  universe[\`system${i + 1}\`] = {};

  // Creating planets
  for (let j = 0; j < nbPlanetPerSystem; j += 1) {
    universe[\`system${i + 1}\`][\`planet${j + 1}\`] = 'something';
  }
}

console.log(universe);

console.log(universe.system3.planet3);

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

Tips for directing attention to a specific row with an input field in JavaScript

I duplicated a table and added an input field for users to search or focus on a specific row. However, there are two issues: When a user enters a row number, the table displays the wrong row - for example, if the user enters 15, the table shows row number ...

HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear. Important: I attempted to use the innerWid ...

Leveraging AngularJS for parent-child communication through bindings in a unique and effective manner

I've come across the following code snippet: <div class="parent"> <div class="child"> and I have two directives, one for parent and one for child. When an event (such as a click) occurs on parent, I want something to happen on child ...

Manipulate the CSS style of the body element in Angular with Typescript using the important tag

Within my Angular application I have implemented the following code to customize the body style: constructor(private elementRef: ElementRef) { } ngOnInit() { this.elementRef.nativeElement.ownerDocument.body.style.overflowY = 'hidden'; ...

What steps can be taken to determine the cause of an abrupt closure of a websocket client?

My browser game utilizes the ws module. However, there seems to be an issue where connections from distant computers randomly close while playing the game. The screen freezes when this happens, but interestingly, I do not encounter this problem when testin ...

Why does this switch case statement fail to effectively replace the elements of the text in order to unravel this JavaScript problem?

Question I need help converting special characters to HTML entities in a string: &, <, >, " (double quote), and ' (apostrophe). My Code function convertHTML(str) { let tempArr = ['a']; let newArr = []; let regex ...

Step-by-step guide on activating a controller function following an Animation in Angular JS

I have hit a roadblock trying to connect a series of animations with a controller action. My goal is to: 1. click on a button/div, 2. Trigger an animation, 3. Once the animation finishes, execute a function in the controller to reset the button/div. I&a ...

IntelliJ does not support the use of newlines within Vue.js component templates

While working with Vue.js in IntelliJ IDEA, I encountered a small problem related to defining component templates. The issue is that IntelliJ seems to struggle when the template spans more than one line and attempts to concatenate them together. For examp ...

Utilize the information from the first page in order to enhance the content on

I have developed a straightforward app that opens a new page displaying the text of the list element clicked by the user. My goal is to pass the device variable to a page named deviceDetails. <ion-list> <ion-item *ngFor="let device of devices" ...

A guide on implementing a TypoError in Node.Js and Discord.Js for enabling a bot to enter a voice channel

Hello there, I'm currently working on a music Bot for Discord using Javascript with Node.Js and I've encountered an issue: This problem arises specifically with the "play" command, but it seems to occur with all commands that involve joining a v ...

Interactive Show Map with Autocompletion Feature

I attempted to implement autocompletion for my application and integrate it with Google Maps, but I'm encountering issues. The code for autocompletion is located in a separate JavaScript file called autocomplete.js. Since I already have a Google Map ...

Is it possible to simultaneously use the same plugin with various configurations and unique names in Vue?

I'm attempting to utilize the Vue Currency Input plugin, specifically with two different configurations simultaneously: import Vue from 'vue' import VueCurrencyInput from 'vue-currency-input' const options = { globalOptions: { ...

Text input field that adjusts its width based on content and remains

I am attempting to design a div that contains a fluid-width textarea. The div should have a width of at least 3em, maximum of 12em, and adjust accordingly to the width of the textarea. I have successfully implemented this. Check out the fiddle. However, w ...

Resetting the positions of images can be done by following these

I'm currently in the process of developing a game and need assistance with implementing a game end function. Can you provide guidance on how to reset all images back to their original positions? ...

Unable to create a flawless circle using Canvas

No matter how hard I try, drawing a perfect circle seems impossible for me. Every time I attempt it, all I manage to create is an ellipse. Check out this code snippet I put together as an example: function canvasClicked(number) { var c = "canvas" + nu ...

Automate the detection of a connected device via USB on a NodeJS server

I created a web interface for a colorimeter by using a NodeJS server that can read USB serial inputs through the serialport npm library. This information is then sent to a local web page. The colorimeter consists of a circuit with a microcontroller that is ...

Is it not possible to generate HTML tags using jQuery and JavaScript in JSF?

I'm currently working with jsf 2.0 and richfaces 4.0 to develop my application. Occasionally, I incorporate jQuery and JavaScript functions for displaying and hiding elements. However, I've encountered an issue when trying to generate tags within ...

Leveraging Flask to pass data to Google Charts with JavaScript

Trying to integrate Google Charts on my website using Flask as the backend. Need help with sending data from Flask to JavaScript. Here's a snippet of where I plan to retrieve data later: @app.route("/") def home(): data = {'Language': &a ...

ASP TextChanged event is not triggering unless the user presses the Enter key or tabs out

My code is functioning correctly, however, the TextChanged event is triggered when I press enter or tab, causing my code to execute. I would like to be able to search for a record without having to press enter or tab. ASP: asp:TextBox ID="txtNameSearch ...

Dealing with problematic hover behaviors in Cypress: A guide

I encountered an issue with Cypress hover functionality while trying to access a sub menu that appears after hovering over a main menu item. The error message I received was This element is not visible because it has CSS property: position: fixed and it&ap ...