Reputation: 832
In my node js program in routes i have created array named list. I have assigned value to array from function declared in model. Code for route is:
var express = require('express');
var router = express.Router();
var questionModel = require('../model/questionModel');
var userModel=require('../model/userModel');
/* GET home page. */
router.get('/', function(req, res, next) {
//declare an array and store the json data
var list=questionModel.getAllQuestions();
for(i=0;i<list.length; i++){
console.log(list[i].submitter);
console.log(userModel.getUserById(list[i].submitter)[0]);
list[i].submitter=userModel.getUserById(list[i].submitter)[0].fname;
}
console.log(list);
//respond with the array
res.json(list);
//res.redirect("../question/" + this_id);
});
module.exports = router;
Here in module i am using local variable as in this class project i am not using any database. My all Models fetch value from one global variable.
This code is work fine on first request. But on first request changing value of list[i].submitter locally value of global value change.
Change in global value creates problem when i get second request. On second request value return from questionModel.getAllQuestions is unnecessarily updated.
Upvotes: 1
Views: 588
Reputation: 18576
Array is always pass by reference in javascript. That's the reason why when you edit the array it affects the original array.
In your case, though you're making a copy of questionModel, still what your getting is a list of objects in your array. The objects reference in both the arrays will refer to same object.
So the changes you make to list[i].submitter
is affecting the original object as well.
If you don't want the update to happen, then you need to deep copy the objects inside array as well like below:
function deepCopy (arr) {
var out = [];
for (var i = 0, len = arr.length; i < len; i++) {
var item = arr[i];
var obj = {};
for (var k in item) {
obj[k] = item[k];
}
out.push(obj);
}
return out;
}
// test case
var questionsModelOriginal = [
{'a' : 1, submitter : "Rias"},
{'b' : 2, submitter : "SO"}
];
var questionsModelCopy = deepCopy(questionsModelOriginal);
Now if you change the property of questions inside questionsModelCopy, it will not modify the global Questions model.
Upvotes: 2