Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why doesn't reassigning the parameter element in forEach work

Not much explanation here so Ill just get straight to the point.

For the following code block:

const items = [
  { id: 1, name: 'one' },
  { id: 2, name: 'two' },
];

const changes = {
  name: 'hello'
}

items.forEach((item, i) => {
  item = {
    ...item,
    ...changes
  }
})

console.log(items) // items NOT reassigned with changes

items.forEach((item, i) => {
  items[i] = {
    ...item,
    ...changes
  }
});

console.log(items) // items reassigned with changes

Why does reassigning the values right on the element iteration not change the objects in the array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  item = {
    ...item,
    ...changes
  }

but changing it by accessing it with the index does change the objects in the array?

  items2[i] = {
    ...item,
    ...changes
  }

and what is the best way to update objects in an array? is items2[i] ideal?

>Solution :

I’d go with a classic Object.assign for this:

const items = [
  { id: 1, name: 'one' },
  { id: 2, name: 'two' },
];

const changes = {
  name: 'hello'
}

items.forEach( (item) => Object.assign(item,changes) )

console.log(items) 

Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources’ properties overwrite earlier ones.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading