Hyrule
Hyrule

Reputation: 645

spread operator to replace value?

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" },

Upvotes: 7

Views: 16051

Answers (1)

Ry-
Ry-

Reputation: 224905

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.

Upvotes: 27

Related Questions