Home > database >  How to handle immutable array on map function in javascript?
How to handle immutable array on map function in javascript?

Time:09-07

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

CodePudding user response:

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.

CodePudding user response:

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)

  • Related