Search code examples
javascriptarraysdictionaryarraylistes6-map

How to handle immutable array on map function in javascript?


Following code is a working logic that receives entries which is an object from an API response. What I am currently doing is to assign entry.listedContent to entryOne.id & entryOne.name properties

I heard that this way, I will be modifying the original items from the array (this.entries). I was told that I should be assigning my final value to a different array, so the original is not touched/modified.

Anyone can advise what is the best practice to handle such cases?

 itemList() {
  return this.entries.map((entry) => {
      if (this.type === "selected") {
        entry.listedContent = entry["entryOne.id"] + " - " + entry["entryOne.name"]
      }
     return entry;
  });
},

Solution

  • Array map does create a new array, but the inner objects will have a unique reference,
    to avoid modifying the original objects you should recreate them copying over the enumerable properties, an example with the spread operator:

    const entries = [{
      listedContent: null,
      id: 1,
      name: 'Alpha'
    }];
    const type = 'selected';
    
    function itemList() {
      const res = entries.map((entry) => {
        if (type === "selected") {
          return {
            ...entry,
            listedContent: entry.id + " - " + entry.name
          }
        }
        return entry;
      });
      return res;
    };
    
    console.log(itemList()); // add results in a new array.
    console.log('original entries >>>', entries)