javascript - when changing value of copied variable it is also changing main variable value in angularjs -


i in strange condition. have array of objects, used angular.foreach modify each object price key value when changing in each changing main array object well.

have on code, understand trying say.

var option_1_val = $scope.options.option_1_val;         var option_2_val = $scope.options.option_2_val;         console.log('genies',sc.genies);          var new_arr = [];         var each ;         each = sc.genies;         angular.foreach(each,function(val,key){             var ob = {};             ob = val;              var pricea = angular.fromjson(ob.price);             console.log('price',pricea);                          var option = option_1_val.replace(" ","-")+","+option_2_val.replace(" ","-");             console.log(option);              ob.price = pricea[option];              console.log(ob);             new_arr.push(ob);         });  option = 'non-vegetarian,' (after calculating)  sc.genies = [{"gs_id":"3","user_id":"25","service_id":"7","price":"{\"vegetarian,bengali\":\"200\",\"vegetarian ,chinese\":\"3100\",\"vegetarian,gujarati\":\"800\",\"vegetarian,italian\":\"100\",\"vegetarian,maharashtrian \":\"100\",\"vegetarian,punjabi\":\"100\",\"vegetarian,-south-indian\":\"300\",\"vegetarian,thai\":\"100 \",\"non-vegetarian,bengali\":\"1100\",\"non-vegetarian,chinese\":\"3100\",\"non-vegetarian,gujarati \":\"100\",\"non-vegetarian,italian\":\"100\",\"non-vegetarian,maharashtrian\":\"100\",\"non-vegetarian ,punjabi\":\"100\",\"non-vegetarian,-south-indian\":\"80\",\"non-vegetarian,thai\":\"100\",\"jain,bengali \":\"2100\",\"jain,chinese\":\"2100\",\"jain,gujarati\":\"4100\",\"jain,italian\":\"100\",\"jain,maharashtrian \":\"100\",\"jain,punjabi\":\"100\",\"jain,-south-indian\":\"800\",\"jain,thai\":\"100\"}","min_price" :"80","max_price":"4100","username":"abdul quadir","email":"abdul.quadir@kiozen.com","rating":"3"}] 

now when repeating sc.genie, have taken in new variable "each" , changing "price" key of each array undefined strange point when see in console value of price in sc.genies changed "undefined". huh!

i hope got point, please me why happening.

thanks

you should use angular.copy when change in each value not affect original value. because of angular.copy assign old value in new variable without reference.

like:

var each ; each = angular.copy(sc.genies); 

instead of

each = sc.genies; 

Comments