I am programming a small Node.js server, to handle surveys. The surveys are stored on the server inside a global array.
When an user answers a question, the client will send the surveyID, the questionID and the answers to the server. On the server I then use Array.find() to determine the correct survey in the array, as well as the correct question inside the survey. Now I add the answers to the object. So far, so good. Works.
But if I wanted to do the manipulation in another function, I cannot simply pass the found survey object into it, because then it's not the same anymore, but a new one, and manipulating it inside the sub-function would not change the global survey object - is that right?
So what I currently do is to pass the IDs into the sub-function and use Array.find in it again. That way it works.
My question is: Is that the correct way to do this? Or is there another way?
Sample Code:
var surveys = [{
id: 117171,
flag_anonym: true,
flag_live: true,
status: "open",
active_question: 0,
questions: [
{
id: 117192,
title: "Wie heißt die Hauptstadt von Deutschland?",
typ: "singlechoice",
answered_by_socket: [ ],
answered_by_user: [ ],
answers: [
{
id: 117188,
title: "Mainz",
votes_anonym: 11
},
{
id: 117189,
title: "Wiesbaden",
votes_anonym: 0
},
{
id: 117190,
title: "Berlin",
votes_anonym: 1
},
{
id: 117191,
title: "München",
votes_anonym: 0
}
]
}
]}];
function updateSurvey(data) {
var survey = surveys.find(function (s) {
return s.id === data.survey_id;
});
if (typeof survey !== "undefined") {
if(survey.flag_live) {
// live survey, question can only be answered if active
if (survey.active_question < survey.questions.length) {
var question = survey.questions[survey.active_question];
if (data.question_id === question.id) {
answerQuestion(data);
}
}
}else {
// question can always be answered
answerQuestion(data);
}
}
}
function answerQuestion(data){
// I have to do Array.find again
var survey = surveys.find(function (s) {
return s.id === data.survey_id;
});
var question = survey.questions.find(function (s) {
return s.id === data.question_id;
});
question.answered_by_socket.push(data.socket_id);
if (data.user_id) {
question.answered_by_user.push(data.user_id);
}
// update answers
question.answers = question.answers.map(function (a) {
for (var i = 0; i < data.answers.length; i++) {
var answer = data.answers[i];
if (a.id === answer.id) {
if (answer.checked) {
a.votes_anonym++;
}
return a;
}
}
return a;
});
}