Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove object by inherited object id in Array

This is my parent array, I need to remove the whole object when there is an id match the selectedData -> personId

 const [parentArr, setParentArr] = React.useState([
    {
      date: " Mon Aug 08 2022",
      selectedData: { personId: 2233, personName: "mary" }
    },
    {
      date: " Mon Aug 08 2022 ",
      selectedData: { personId: 2223, personName: "jane" }
    }
  ]);

This is the function I use to remove an item but it returns selectedData object

  const removeItem = () => {
        const hardcodeId = 2223;
        // for this is use hardcoded id here
        const selectedDataCopy = [...parentArr];
        const getSelectedDataArrays = selectedDataCopy?.map(
          (item, i) => item.selectedData
        );
        const getSelectedDataArraysRemove = getSelectedDataArrays?.filter(
          (item, i) => item.personId !== hardcodeId
        );
        setParentArr(getSelectedDataArraysRemove)
      };

I expect an array like this after removeItem triggered

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const [parentArr, setParentArr] = React.useState([
    {
      date: " Mon Aug 08 2022",
      selectedData: [{ personId: 2233, personName: "mary" }]
    }
  ]);

>Solution :

item.selectedData you should write

you don’t need to return with map just write this

const getSelectedDataArraysRemove = data?.filter(
      (item, i) => item.selectedData.personId !== 2223
    );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading