0
\$\begingroup\$

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; }

asked Mar 20, 2021 at 13:28
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This could be accomplished via an XOR, or boolean not equal in other words.

const people = [
 {
 "name": "Olivia",
 "lead": true
 },
 {
 "name": "Gary",
 "lead": false
 },
 {
 "name": "Adam",
 "lead": false
 }
]
const toggleLead = (name) =>
 [...people].map(person =>
 ({
 ...person,
 lead: person.lead !== (person.name===name)
 })
 )
console.log(toggleLead('Gary'))
.as-console-wrapper { max-height: 100% !important; top: 0; }

answered Mar 20, 2021 at 13:46
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, it works great and it is a lot more concise \$\endgroup\$ Commented Mar 20, 2021 at 13:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.