Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to return one random reply from a db in Javascript

When trying to create an API endpoint for, in this case, a sandbox environment, it currently returns the entire file as a result. What I would like is for it to return only one group of info but am new to JS and cannot figure out how to do it.

  app.get("/sandbox", function (req, res) {
    var sandbox = require("./api/sandbox.json");

    console.log("GET /sandbox Received: " + JSON.stringify(req.body));
    {
      return res.send(sandbox);
    }
  });

/api/sandbox.json is currently ~250 items formatted. Each contains three fields grouped. So "id" "response" and "footer". How do I get only one group at random to come back as a result?

For this, I really don’t know where to start. I’m just excited I got this far.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The following solution assumes that sandbox.json contains the valid array of elements.

You may use the following expression to pick the random element of the sandbox array

Math.floor(Math.random() * sandbox.length)

The resulting code could look more or less like this

app.get("/sandbox", function (req, res) {
    const sandbox = require("./api/sandbox.json"); 
    const result = sandbox[Math.floor(Math.random() * sandbox.length)];
    return res.send(result);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading