Will
Will

Reputation: 11

How do I use a random number from a variable in a JSON index call?

I am creating a slideshow using image URLs from a JSON containing about 100 images. I only want to select 5 random images for the slideshow each time the page loads. The html is styled inside a style tag in the EJS file that loads on the home page. How would you make the JSON index call take a random number in range 1-100?

Here is my app.js file, (I'm using express):

var express = require("express");
var app = express();
var request = require("request")
app.set("view engine", "ejs")

app.get("/results", function(req, res){
    res.render("search")
});

app.get("/", function(req, res){
    
    request('https://www.reddit.com/r/pics.api', function (error, response, body){
        if(!error && response.statusCode == 200) {
            var data = JSON.parse(body)
            var num = Math.floor(Math.random() * 101)
            res.render("fullscreen", {data: data, num: num});
            console.log(data["data"]["children"][0]["data"]["url"])
        }   
    });
});

app.listen(3000, function(){
    console.log("Server has started!!!");
});

Here is the relevant snippet of my style code:

  .slideshow li:nth-child(1) { 
  background-image: url(<%=data["data"]["children"][num]["data"]["url"] %>); 
}

When I run my code with a whole number in place "num" it works great, but when I run it as shown above I get: "Cannot read property 'data' of undefined". How can a make "num" a random number inside the JSON index call?

Upvotes: 0

Views: 463

Answers (1)

Alexander Smirnov
Alexander Smirnov

Reputation: 408

There are not always 100 of data items. Use this formula for num:

const num = Math.floor(Math.random() * data["data"]["children"].length);

Check this

Upvotes: 1

Related Questions