Search code examples
javascriptmultidimensional-arrayassociative-array

Unacceptable value in associative array in Javascript


I set value in associative array in 2D array in JavaScript. I used a following source code:

var properties = {
  "isBold": false,
  "isItalic": false,
  "isUnderline": false
};

// Creation of 2D array, 6x6
var listOfProperties = new Array(6);
for (var i = 0; i < listOfProperties.length; i++) {
  listOfProperties[i] = new Array(6);
}

// Population of listOfProperties with properties
for (var row = 0; row < listOfProperties.length; row++) {
  for (var col = 0; col < listOfProperties.length; col++) {
    listOfProperties[row][col] = properties;
  }
}

var property = listOfProperties[2][2];
property.isBold = true; // I would like to populate property isBold
console.log("property > " + property.isBold);

var property = listOfProperties[0][0];
console.log("property > " + property.isBold);

I created 2D array which I populated with properties (associative array, all values are false). Then I set a true for isBold for *listOfProperties[2][2]**.

But why isBold in listOfProperties[0][0] includes true instead false?


Solution

  • You need to fill the 2D array of copies of the object, not the reference:

    var properties = {
      "isBold": false,
      "isItalic": false,
      "isUnderline": false
    };
    
    // Creation of 2D array, 6x6
    var listOfProperties = new Array(6);
    for (var i = 0; i < listOfProperties.length; i++) {
      listOfProperties[i] = new Array(6);
    }
    
    // Population of listOfProperties with properties
    for (var row = 0; row < listOfProperties.length; row++) {
      for (var col = 0; col < listOfProperties.length; col++) {
        listOfProperties[row][col] = Object.assign({}, properties);
      }
    }
    
    var property = listOfProperties[1][1];
    property.isBold = true; // I would like to populate property isBold
    console.log("property > " + property.isBold);
    
    var property = listOfProperties[0][0];
    console.log("property > " + property.isBold);

    For more details, check this.