ANEES
ANEES

Reputation: 318

value of array gets updated on updating Property value

I have following code in JS file

    var listOfCountries = [];
    var Country = {};
    Country = { "CountryCode": null, "SerialNo": 0, "FrzInd": false }

    for (var i=0; i < $('#ulCustomCountryList li').length; i++) {
      Country.CountryCode = $("#countryCode_" + i).val();
      Country.SerialNo = $("#serialNo_" + i).val();
      listOfCountries.push(Country);
    }

in first iteration: when countryCode_0 is "IND" then listOfCountries[0].CountryCode = "IND" , in second Iteration when countryCode_1 is "AUS" then listOfCountries[1].CountryCode = "AUS" but it alse updates the value of listOfCountries[0].CountryCode to listOfCountries[0].CountryCode = "AUS"

Upvotes: 1

Views: 47

Answers (1)

Jitesh Manglani
Jitesh Manglani

Reputation: 485

As Objects are a reference. All reference to object would be updated. you push the same object every iteration so you have two ways to fix it

1- Create new object on every iteration As following:

  var countriesCount = $('#ulCustomCountryList li').length; //- 1
  listOfCountries =[];
  for (var i = 0; i < countriesCount; i++) {

    var Country = { "CountryCode": null, "SerialNo": 0, "FrzInd": false }
    Country.CountryCode = $("#countryCode_" + i).val();
    Country.SerialNo = $("#serialNo_" + i).val();
    listOfCountries.push(Country);

  }

or 2 - use Object.assign({},Country) for copy the object every iteration.

     var countriesCount = $('#ulCustomCountryList li').length; //- 1
       var listOfCountries = [];
        var Country = {};
        Country = { "CountryCode": null, "SerialNo": 0, "FrzInd": false }

        for (var i=0; i < countriesCount; i++) {
          var copy = Object.assign({}, Country);
          copy.CountryCode = $("#countryCode_" + i).val();
          copy.SerialNo = $("#serialNo_" + i).val();
          listOfCountries.push(copy);
        }

Upvotes: 1

Related Questions