meez
meez

Reputation: 4769

How write my condition when using destructuring when mapping over an Array of objects

I am working with the following array of objects:

var persons: {
    label: string;
    value: string;
}[]

I iterate over the array like this:

   {persons?.map((person) => {
      return (
        <button
          key={person.value}
          data-active={value === person.value}
        >
          {person.label}
        </button>
      );
    })}

Now I use destructuring so I don't have to write person.value etc all the time, so I don't have redundant code:

   {persons?.map(({ value, label }) => {
      return (
        <button
          key={value}
          // data-active={value === person.value}
        >
          {label}
        </button>
      );
    })}

But how do I get my boolean now data-active={value === person.value} (since now {value === value} is always true)?

Upvotes: 1

Views: 235

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074188

If you want to use destructuring, you need to avoid shadowing your existing value variable. You can use renaming in your destructuring pattern:

{persons?.map(({ value: thisValue, label }) => {
   return (
     <button
       key={thisValue}
       data-active={value === thisValue}
     >
       {label}
     </button>
   );
})}

...but I'd lean toward renaming your outer value variable instead, perhaps calling it activeValue. Then you don't need the renaming:

const activeValue = /*...*/;
// ...
{persons?.map(({ value, label }) => {
   return (
     <button
       key={value}
       data-active={activeValue === value}
     >
       {label}
     </button>
   );
})}

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

Use an alias for value (I've used v), so the destructured value won't shadow the value from the outer scope:

 {persons?.map(({ value: v, label }) => {
    return (
      <button
        key={v}
        data-active={value === v}
      >
        {label}
      </button>
    );
  })}

Upvotes: 1

Related Questions