I am runing this function that finds an object in an array and toggles the boolean lead
property.
I am actually doing this in react so in there I do change the data via state and in the end if I run it again it would toggle Gary
true/false, so it works fine.
My question is regarding the JavaScript code itself, it feels a bit convoluted, is there a better way?
const people = [
{
"name": "Olivia",
"lead": true
},
{
"name": "Gary",
"lead": false
},
{
"name": "Adam",
"lead": false
}
]
const toggleLead = (name) => {
const values = [...people].map(person =>
person.name === name
? {
...person,
lead: !person.lead
}
: { ...person }
)
return values
}
console.log(toggleLead('Gary'))
.as-console-wrapper { max-height: 100% !important; top: 0; }