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

293
Visualizações
Looping through a JSON array to get a Random value (Javascript)

I am trying to loop through my JSON array and get a random value from it.

Here is my Json Code:

{"cities":[{"city":"St.John","xCoor":931,"yCoor":349},{"city":"Halifax","xCoor":844,"yCoor":424},{"city":"Charlottetown","xCoor":838,"yCoor":407},{"city":"Fredericton","xCoor":800,"yCoor":422},{"city":"Quebec","xCoor":734,"yCoor":427},{"city":"Ottawa","xCoor":685,"yCoor":459},{"city":"Toronto","xCoor":655,"yCoor":483},{"city":"Winnipeg","xCoor":420,"yCoor":430},{"city":"Regina","xCoor":336,"yCoor":417},{"city":"Edmonton","xCoor":250,"yCoor":364},{"city":"Victoria","xCoor":111,"yCoor":398},{"city":"Whitehorse","xCoor":115,"yCoor":235},{"city":"Yellowknife","xCoor":285,"yCoor":271},{"city":"Iqaluit","xCoor":645,"yCoor":243}]}

In this case I want to loop through the "Cities" array and get a random "city".

This is my code to get the Json Data:

function getJsonData() {
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function () {
    if (xhttp.readyState==4 && xhttp.status==200) {
        schedule = JSON.parse(xhttp.responseText);
    }
}

xhttp.open("GET", "capitals.json", true);
xhttp.send();}

This is what I have written to try and get the a Random City from the Cities array:

function drawPlanes() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var cityNames = schedule["cities"];

for(var i = 0; i < cityNames.length; i++) {
    var obj = cityNames[i];
    var randomCity = obj.city[Math.floor(Math.random()*obj.city)];
    console.log(randomCity);
}}

In summary, I essentially just want to loop through this Json Array and get a Random City Value, for example: in the console it just prints lets say "Quebec", but the problem here is that what I wrote is not working. Hopefully what I am asking is clear enough.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could [index] a random city with Math.random(), using cities.length as your max value.

const data = {"cities":[{"city":"St.John","xCoor":931,"yCoor":349},{"city":"Halifax","xCoor":844,"yCoor":424},{"city":"Charlottetown","xCoor":838,"yCoor":407},{"city":"Fredericton","xCoor":800,"yCoor":422},{"city":"Quebec","xCoor":734,"yCoor":427},{"city":"Ottawa","xCoor":685,"yCoor":459},{"city":"Toronto","xCoor":655,"yCoor":483},{"city":"Winnipeg","xCoor":420,"yCoor":430},{"city":"Regina","xCoor":336,"yCoor":417},{"city":"Edmonton","xCoor":250,"yCoor":364},{"city":"Victoria","xCoor":111,"yCoor":398},{"city":"Whitehorse","xCoor":115,"yCoor":235},{"city":"Yellowknife","xCoor":285,"yCoor":271},{"city":"Iqaluit","xCoor":645,"yCoor":243}]};

const randomCity = data.cities[Math.floor(Math.random() * data.cities.length)];

console.log(randomCity);

Edit

If you only want to get the city name, you can get the city property with .city.

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