Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spread operator to replace value?

Tags:

javascript

Why does the spread operator replace the value of 'Stratford' with 'HB woodlawn' here? How does this work?

const editName = (oldName, name, arr) =>
  arr.map(item => {
    if (item.name === oldName) {
      return {
        ...item,
        name
      }
    } else {
      return item
    }
  })

let schools = [
  { name: "Yorktown"},
  { name: "Stratford" },
  { name: "Washington & Lee"},
  { name: "Wakefield"}
]
let updatedSchools = editName("Stratford", "HB Woodlawn", schools)
console.log( updatedSchools[1] ) // { name: "HB Woodlawn" }
console.log( schools[1] ) // { name: "Stratford" },
like image 719
Hyrule Avatar asked Nov 30 '22 09:11

Hyrule


1 Answers

What it comes down to is this:

const oldObject = { name: 'Stratford' };
const newObject = { ...oldObject, name: 'HB Woodlawn' };

which you can think of as expanding oldObject’s properties into the new object literal:

const newObject = { name: 'Stratford', name: 'HB Woodlawn' };

Properties with the same key in a literal get the value of the last one.

like image 73
2 revs Avatar answered Dec 07 '22 22:12

2 revs