I have an array that I want to search and just place one item that matches in a search like so:-
Array and code example :
const test = [
{ id: 0, title: 'test1', seen: false },
{ id: 1, title: 'test2', seen: false },
{ id: 2, title: 'test3', seen: true },
];
I need to be able to search the test array for the ID:2 and set it to ‘seen:true’
I have tried :
const [testarray, testTestArray] = usestate(test);
const checkID = 2;
const updateStatus = (checkID) => {
const new_data = testarray.data.map(id => {
if (id === checkID) {
// No change
return id;
} else {
return {
...id,
seen: true,
};
}
});
setTest(new_data);
I have played with it in different ways and the closest I have got is changing all of them to ‘seen: true’?
What am I not getting here?
Thanks
2
Answers
Let’s fix that:
Errors were:
I hope everything is understood.
You are checking
id
with thecheckID
which will never be equal because you are comparingobject
(each individual object in array) withnumber
.You have to compare it with
id.id
or for better naming conventionobj.id
withcheckID
.CODESANDBOX
You can more simpliyfy it as: