Champion
Champion

Reputation: 774

How to change all array while updating one element in javascript?

I need to have always only one element true in array.

Supposed I have an array

let data = [
  { letter: "a", id: 1, bool: false },
  { letter: "b", id: 2, bool: false },
  { letter: "c", id: 3, bool: false},
  { letter: "d", id: 4, bool: false },
];

every time I click on an element I need to change it to true while all other to false. I have a function

const updatedArray = data.map((item) => {
  if (item.id === id) {
    return {
      ...item,
      bool: true,
    };
  }
  return item;
});

But it works as a toggle for clicked element.

Upvotes: 2

Views: 628

Answers (2)

Saeed Shamloo
Saeed Shamloo

Reputation: 6554

Your problem is here: return item;,you are actually returning the previous value and just updating the bool property of item which has the same id as id variable, but you need to toggle the bool property of all the items, you can acheive your goal like this:

const updatedArray = array.map((item) => ({...item, bool: item.id === id}));

Upvotes: 3

Wais Kamal
Wais Kamal

Reputation: 6180

You need to also set the item's bool to false if it is not the selected item, not just set the selected item's bool to true. This should work:

const id = 3 (clicked item)
const updatedArray = array.map(item => {
  if (item.id === id) {
    return {
      ...item,
      bool: true
    };
  }
  return {
    ...item,
    bool: false
  }
});

Upvotes: 0

Related Questions