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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.