简体   繁体   中英

How to push a map in array and clear the original map to store more data

I am using one map to store name and number as K,V pair. I am using a for loop to run and store multiple data sets in this map. The expected behavior is a loop that will be executed and values will be stored in the map, then I want to push this map into an array and clear the original map to store another data set. My problem is when I try to clear the original map it wipes the data that has been saved in an array as well. I tried using deep copy but it is not working. Is there any other way to do it?

Below is my code.

for (let GUId of GUIIds) {
          if (GUId.toLowerCase() != parentGUI.toLowerCase()) {
            await browser.driver.switchTo().window(GUId);

            for (let j = 0; j < (await this.elePanels.count()); j++) {
              if (j != 0) await this.elePanels.get(j).click();

              let name = await this.elePanels
                .get(j)
                .getWebElement()
                .findElement(By.xpath(".//mat-panel-title"))
                .getText();

              let number = await this.elePanels
                .get(j)
                .getWebElement()
                .findElement(
                  By.xpath(
                    ".//span[@class='ng-star-inserted']//following-sibling::span"
                  )
                )
                .getText();
              await map.set(name, number);
            }
            await actualData.push(map);
            await map.clear();
            await browser.driver.close();
            await browser.driver.switchTo().window(parentGUI);
          } 

          return actualData; 

Array is a reference type in Javascript and when a variable is assigned to it, it points to the reference of the array, not the value. You are getting this error because actualData stores the reference of map array not the value. To fix this, use array.slice() because array.slice() returns the value of the array and not a reference.

    const actualData = [];
    ...
    actualData.push(map.slice(0))

You can read more about it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM