I'm trying to make a web app that takes in the names of several people and assigns each one a friend but am running into an issue assigning the friends.
The issue I'm running into is that it properly assigns the first few people friends, but always crashes on the second last person in the array and displays the error message
TypeError: Cannot set property 'friend' of undefined.
Here is a snippet from my app.js code.
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
let participantsObject = {};
let participantsArray = [];
let randomNumber;
app.get("/new", function(req, res) {
res.sendFile(__dirname + "/new.html");
});
app.post("/new", function(req, res) {
participantsObject[req.body.person] = {};
participantsArray.push(req.body.person);
res.redirect("/new");
});
app.get("/setup", function() {
let size = participantsArray.length;
let participantsWithoutAGifter = participantsArray;
for (var i = 0; i < size; i++) {
randomNumber = Math.floor(Math.random() * participantsWithoutAGifter.length)
participantsObject[participantsArray[i]]["friend"] = participantsWithoutAGifter[randomNumber];
participantsWithoutAGifter.splice(randomNumber, 1);
}
console.log(participantsObject);
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
And here is my new.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="post">
<input type="text" name="person" placeholder="Enter participant name" autofocus>
<button type="submit">Add</button>
<button type="button"><a href="/setup">Finished</a></button>
</form>
</body>
</html>
Ideally, it would be able to assign all participants a friend and then log the entire object.
Any help would be much appreciated, thanks in advance.