Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am in a strange condition. I have an array of objects, I used angular.forEach to modify each object price key value but when I am changing it in each it is also changing main array object as well.

Have a look on code, you will understand then what I am trying to 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":"[email protected]","rating":"3"}]

now when I am repeating sc.genie, I have taken it in a new variable already "each" and then I am changing "price" key of each array to undefined but strange point is when I see in console value of price in sc.genies is also changed to "undefined". Huh!

I hope you got my point, please help me why is that happening.

Thanks

like image 850
Raghvendra Singh Avatar asked Oct 29 '25 01:10

Raghvendra Singh


1 Answers

You should use angular.copy then when change in each value not affect to 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;
like image 166
Shaishab Roy Avatar answered Oct 30 '25 21:10

Shaishab Roy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!