How to handle immutable array on map function in javascript?

142 Views Asked by At

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;
  });
},
2

There are 2 best solutions below

0
maioman On BEST ANSWER

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)

4
Rohìt Jíndal On

Array.map() method creates a new array instead of modifying the input array.

Live Demo :

const entries = [{
  listedContent: null,
  id: 1,
  name: 'Alpha'
}];
const type = 'selected';

function itemList() {
  const res = entries.map((entry) => {
      if (type === "selected") {
        entry.listedContent = entry.id + " - " + entry.name
      }
      return entry;
  });
  return res;
};

console.log(entries); // Original array not modified.
console.log(itemList()); // add results in a new array.