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" },
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With