0

I have this array:

let myArray = [
  {
    id: 20,
    comments: {
      TICOL: 'This is a new comment'
    },
    result: 'my results'
  }
];

Now I'm trying to update the TICOL property by first creating a copy of the array like this:

let someArray = [...myArray];

let finalArray = someArray.map(obj => {
  obj.comments.TICOL = obj.comments.TICOL.replaceAll('new', 'TEST')
});

But finalArray is always [undefined]. Can anyone tell me what I'm missing? Thanks

hanch
  • 4,195
  • 2
  • 7
  • 32
Devmix
  • 954
  • 1
  • 19
  • 45
  • [You never return anything from `.map()`](https://stackoverflow.com/q/28889450), hence why the array it returns has `undefined` in it - the implicit value of function calls. – VLAZ Sep 30 '20 at 22:41
  • 2
    You aren't returning anything. But why use map anyway? If you want to mutate, use a method for plain iteration like forEach – Snow Sep 30 '20 at 22:41
  • 1
    Also an important point; `[...myArray]` creates only a shallow copy. Since the elements are objects, mutating their properties will affect both arrays. – Taplar Sep 30 '20 at 22:44
  • Note that `[...myArray]` returns a shallow copy, elements in the second array are simply references the objects in the first array so modifying the objects in the first array also modifies those in the second (because they're the same objects). – RobG Sep 30 '20 at 22:45
  • @Taplar what will be another way to mutate my array? – Devmix Sep 30 '20 at 22:45
  • 1
    You mean, how to do a deep copy? `var someArray = JSON.parse(JSON.stringify(myArray));` – Taplar Sep 30 '20 at 22:46
  • @Taplar thank you mate! – Devmix Sep 30 '20 at 22:51
  • @Taplar—that has several issues that need to be explained, see [*What is the most efficient way to deep clone an object in JavaScript?*](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/122704#122704) and many similar questions. – RobG Oct 01 '20 at 00:37

1 Answers1

1

You have to return the new value within map method:

let finalArray = someArray.map(obj => {
   obj.comments.TICOL = obj.comments.TICOL.replaceAll('new', 'TEST');
   return obj;
});
hanch
  • 4,195
  • 2
  • 7
  • 32