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.
Solution 1:
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}));