node.js - How can I prevent changes on the objects returned by the module functions from changing the module data itself in Javascript? -


i working node first time , have 2 modules. 1 module defines array of objects, , has functions exported use in other module - including lookupbyid, lookupbylastname, , addemployee.

my issue when call functions module 1 in module 2, return objects original array , assign objects variable, , modify variable, modifies original data. please see following code:

module 1:

const = require('underscore') var data = [   {id:1, firstname:'john', lastname:'smith'},   {id:2, firstname:'jane', lastname:'smith'},   {id:3, firstname:'john', lastname:'doe'}, ]  exports.lookupbyid = function (given_id) {   var found_id = us.findwhere(data, {id:given_id});   return found_id; } 

module 2:

const employeefunctions = require("./employeemodule"); var id_2_answer = employeefunctions.lookupbyid(2); id_2_answer.firstname = 'mary' console.log(employeefunctions.lookupbyid(2)) 

as can see, changed name of jane mary. though assigned object variable, changing variable changed original object data, verified printing lookupbyid function second time.

can me understand why happens? can me understand possible ways prevent happening? able assign object variable, , able change values within variable without affecting original data.

thank you!

in js objects assigned reference so:

var foo = {bar:1}; var baz = foo; baz.bar; // 1 baz.bar = 2; foo.bar; // 2 

use object.assign clone objects instead:

var foo = {bar:1}; var baz = object.assign({}, foo); baz.bar; // 1 baz.bar = 2; foo.bar; // 1 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -