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