Issue
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
Solution
You are checking id
with the checkID
which will never be equal because you are comparing object
(each individual object in array) with number
.
You have to compare it with id.id
or for better naming convention obj.id
with checkID
.
const updateStatus = (checkID) => {
console.log(checkID);
const new_data = testarray.map((obj) => {
if (obj.id === checkID) {
return {
...obj,
seen: true
};
} else {
return obj;
}
});
setTestArray(new_data);
};
You can more simpliyfy it as:
const updateStatus = (checkID) => {
const new_data = testarray.map((obj) => ({
...obj,
seen: obj.id === checkID ? true : obj.seen
}));
setTestArray(new_data);
};
Answered By - DecPK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.