Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
Crear una matriz de objetos con un número aleatorio de propiedades

Estoy tratando de crear una matriz de objetos que se completarán con propiedades aleatorias. Quiero que todos los objetos se vean así
{ systemStar: "something random", planets: ["random1", "random2", etc]} Actualmente tengo el siguiente código

 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) }

Esto hace un gran trabajo al crear los objetos que quiero con el siguiente formato, sin embargo, systemPlanets es solo uno, en lugar de un número aleatorio. Intenté hacer un bucle for doble pero la sintaxis me eludía. ¿Cómo puedo obtener una matriz de cadenas aleatorias dentro de mi bucle for?
Variables añadidas para mayor claridad.

 let starList = [ "Red-Giant", "Red-Supergiant", "Blue-Giant", "White-Dwarf", "Yellow-Dwarf", "Red-Dwarf", "Brown-Dwarf", ]; let planetList = [ "Rocky", "Temperate", "Ocean", "Frozen", "Lava", "Gas" ];
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Lo que necesita es crear otro ciclo de número aleatorio que sea menor que el número de planetas disponibles y crear una matriz de planetas en ese ciclo:

 let starList = [ "Red-Giant", "Red-Supergiant", "Blue-Giant", "White-Dwarf", "Yellow-Dwarf", "Red-Dwarf", "Brown-Dwarf", ]; let planetList = [ "Rocky", "Temperate", "Ocean", "Frozen", "Lava", "Gas" ]; const letThereBeLight = () => { let universe = [] const starNumber = 5; let randomNumberOfPlanets = Math.floor(Math.random() * 6); for (let i = 0; i < starNumber; i++) { const planets = []; // generate list of planets with at least 1 planet for(let p = 0, max = ~~(Math.random() * planetList.length - 1) + 1; p < max; p++) planets[planets.length] = planetList[~~(Math.random() * planetList.length)]; universe.push({ systemStar: starList[Math.floor(Math.random() * starList.length)], systemPlanets: planets }) } console.log(universe) } letThereBeLight();

about 4 years ago · Juan Pablo Isaza Relatório

0

Intente usar Array.from({length:5}) para crear una matriz de 5 elementos. y reemplace 5 con un número aleatorio usando Math.random() * 5 Math.floor() para redondearlo a un número cercano, agregue agregue uno para al menos crear un planeta. luego map a valores en la matriz de origen `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)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda