skip to Main Content

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


  1. Let’s fix that:

    const [array, setArray] = useState(test);
    const checkID = 2;
    
    const updateStatus = (checkID) => {
      const new_data =  array.map(item => {
        // here was the major mistake
        if (item.id === checkID) {
          return {
            ...item,
            seen: true,
          };
        } else {
          // No change
          return item;
        }
      });
      setArray(new_data);
    }
    

    Errors were:

    • Using different names.
    • not using the item property but the item itself in comparison.
    • if-else blocks were inverted respect to what is asked.

    I hope everything is understood.

    Login or Signup to reply.
  2. 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.

    CODESANDBOX

      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);
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search