Generating a collection of objects containing a variable number of attributes

I want to generate an array of objects filled with random properties. Each object should have the following structure:

{ systemStar: "something random", planets: ["random1", "random2", etc]}
Here's the current code I am using:

const letThereBeLight = () => {
  let universe = []
  const starNumber = 5;
  let randomNumberOfPlanets = Math.floor(Math.random() * 6);
  for (let i = 0; i < starNumber; i++) {
    universe.push({
      systemStar: starList[Math.floor(Math.random() * lengthOfStarList)],
      systemPlanets: [planetList[Math.floor(Math.random() * lengthOfPlanetList)]]
    })

  }

  console.log(universe)
}

The code successfully creates the desired objects, but the systemPlanets only contains one instead of a random number. I attempted a double for loop but struggled with the syntax. How can I generate an array of random strings within my for loop?
Additional variables for clarity:

let starList = [
  "Red-Giant",
  "Red-Supergiant",
  "Blue-Giant",
  "White-Dwarf",
  "Yellow-Dwarf",
  "Red-Dwarf",
  "Brown-Dwarf",
];
let planetList = [
  "Rocky",
  "Temperate",
  "Ocean",
  "Frozen",
  "Lava",
  "Gas"
];

Answer №1

One way to generate an array with 5 elements is by using the Array.from({length:5}) method. To make it more dynamic, you can replace the number 5 with a random value obtained by utilizing Math.random() * 5 followed by Math.floor() to round it down to the nearest whole number. Moreover, adding 1 ensures that at least one planet is created. Finally, you can use the map function to map the randomly selected values to the elements in the source array called `planetList`.

let starList = [
  "Red-Giant",
  "Red-Supergiant",
  "Blue-Giant",
  "White-Dwarf",
  "Yellow-Dwarf",
  "Red-Dwarf",
  "Brown-Dwarf",
];
let planetList = [
  "Rocky",
  "Temperate",
  "Ocean",
  "Frozen",
  "Lava",
  "Gas"
];
let lengthOfStarList = starList.length;
let lengthOfPlanetList = planetList.length;
let universe = []
const starNumber = 5;
for (let i = 0; i < starNumber; i++) {
    universe.push({
      systemStar: starList[Math.floor(Math.random() * lengthOfStarList)],
      systemPlanets: Array.from({length:Math.floor(Math.random() * 5)+1}).map(x=>planetList[Math.floor(Math.random() * lengthOfPlanetList)])
    })
}
console.log(universe)

Answer №2

To add some variety, consider creating an additional loop that generates random numbers less than the total number of available planets. Within this loop, assemble an array of planets:

let starTypes = [
  "Red-Giant",
  "Red-Supergiant",
  "Blue-Giant",
  "White-Dwarf",
  "Yellow-Dwarf",
  "Red-Dwarf",
  "Brown-Dwarf",
];
let planetTypes = [
  "Rocky",
  "Temperate",
  "Ocean",
  "Frozen",
  "Lava",
  "Gas"
];

const generateUniverse = () => {
  let universe = []
  const numOfStars = 5;
  let randNumPlanets = Math.floor(Math.random() * 6);
  for (let i = 0; i < numOfStars; i++) {
    const planets = [];
    // creating a random list of planets with at least 1 planet
    for(let p = 0, max = ~~(Math.random() * planetTypes.length - 1) + 1; p < max; p++)
      planets[planets.length] = planetTypes[~~(Math.random() * planetTypes.length)];

    universe.push({
      systemStar: starTypes[Math.floor(Math.random() * starTypes.length)],
      systemPlanets: planets
    })

  }

  console.log(universe)
}
generateUniverse();

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

Padding for the initial element in a carousel display

I am currently working on implementing owl carousel with stage padding. My goal is to use the carousel with loop:false, and have the first item displayed without left padding, while maintaining consistent padding for both items on the left and right after ...

Error message HMR Webpack was found to be invalid

When using Webpack, I keep encountering the following error message: Invalid HMR message, along with a lengthy JSON string. Unfortunately, I couldn't find any helpful resources to assist me in debugging this issue. Do you have any suggestions? https ...

Perform a task only once during several scroll events and disable additional scrolling

I want to add scrolling functionality similar to the Google Inbox landing page: On that page, no matter how fast or how many times you scroll the wheel, it only counts as one scroll and moves to the next step. This sounds simple, but it's actually qu ...

Escaping quotes in JavaScript

After receiving a JSON object in the following format: result: { image: "..." title: "text text \"text\"" } I am currently utilizing underscore.js to render the template, but I am encountering an issue where the title displays with the escape ...

Problem with using Twitter Bootstrap in IE11 when Browser Profile Enterprise is enabled

I am facing an issue with a Bootstrap 3 web page. Some machines have IE configured to load intranet pages in Enterprise profile mode, while others have the default Desktop profile set in IE11. This configuration has caused the layout to break completely. ...

Checking the strength of passwords containing special characters

I'm looking to enhance my password validation by including special characters. However, I'm running into an issue where using '%' is causing problems. How can I properly implement validation for special characters? $.validator.addMetho ...

Error occurs when attempting to access second level route in Vue directly

I am currently utilizing vue-router within my vue application. The application consists of the following routes: const routes = [ {name: "home", path: "/", component: Home}, {name: "user", path: "/user", component: User}, {name: "edit-user", p ...

What could be the reason for my CORS headers not aligning even though they appear to be identical?

I encountered an issue while using passport js with REACT. When trying to fetch the logged in user data, I faced a problem where the cors header of fetch didn't match even though they are identical. Here is the endpoint I am sending the fetch request ...

Showing the child component as undefined in the view

Within my Angular application, I encountered an issue involving a parent component named DepotSelectionComponent and its child component SiteDetailsComponent. The problem arises when an event called moreDetails is emitted to the parent component, triggerin ...

Find the total number of duplicate elements in a JavaScript array

I'm using an ajax call to retrieve values from a JSON structure and pushing them into a JavaScript array with .push for each iteration. However, I have multiple instances of the same value (e.g. person's name) in the array and I want to count the ...

Managing state within SolidJS components using Immer's "produce" for nested state handling

I've been working on a SolidJS application where I store a large JSON object with nested objects. For undo and redo actions, I'm using Immer to generate patches. Although technically I'm storing a class with multiple layers of nesting, Immer ...

Error: Sorry, there was an issue with the code (React)

I'm attempting to build a React project without Node, and I'm trying to call a JS file from an HTML file. This is just a simple example for learning purposes. However, I keep encountering the Uncaught SyntaxError: Unexpected token '<&apos ...

What is the best way to retrieve the value of a custom attribute from a dropdown list using either JavaScript or jQuery?

I have a dropdown list on a web form and I need to have a 'hidden' variable for each item in the list that can be retrieved using the onchange event on the client side. To achieve this, after databinding the dropdownlist, I am setting a custom at ...

Creating a foolproof image polling platform: A step-by-step guide

I'm in the process of creating a webpage on my site that allows users to view a collection of images. The goal is for each registered user to choose one picture as their favorite, increasing that picture's score by one. The image with the highest ...

What is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...

Obtaining IP Address with Jquery or Phonegap: A Guide for Cross Platform Development

Is there a way to retrieve the IP address using Jquery or Phonegap? I am currently working on an application that is compatible with Android, iPhone, and Windows platforms. I'm in need of a solution to locate the IP address of a request. ...

How to present MongoDB data on the frontend using Node.js without relying on a framework

As someone with experience in HTML, CSS, and JavaScript, I am new to Node.js and server-side programming. Although I can serve HTML pages using FileSystem and the request.url stream in NodeJS, I need assistance as I navigate through my first server-side la ...

Is there a table that allows users to input percentages?

Looking for help with a table that has 2 columns: "Activities" and "Average % of Time". Users need to input a % value for each activity in the "Average % of Time" column. There are 7 rows for activities. The goal is to ensure that the sum of the % values f ...

Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure: results = [ {name: 'Ana', country: 'US', language: 'EN'}, {name: 'Paul', country: 'UK', language: 'EN'}, {name: & ...

Connect parent-child models with checkboxes

Currently, I am working on an application where I need to link checkboxes for a role-based menu. The challenge lies in dealing with parent-child checkboxes and ensuring that the values of checkboxes are checked based on user input 1, 1.1, 1.2, 2, 3. Despi ...