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

Array.filter is not working properly for the array, include objects

I have an Array like this.
enter image description here

I need branchId only.so I use the filter method to filter this array and store branchId in react state.

 const [branchID,setBranchID]=React.useState([]);
 const tempTwo=[
       {
          branchId: "61b25e0ae177d62ce4cb3b47",
          branchName: "Shopzier Malabe Branch"
       },
       {
          branchId: "61aa4f802aed6f0022102a99"
          branchName: "Test Branch New Update"
      },
      {
         branchId: "619f346f17b5522b184d5c01",
         branchName: "Shopzier Main Branch Update Trest12"
      }
   ]
 React.useEffect(()=>{
    setBranchID([...tempTwo.filter(item=>item.branchId)])
  },[])

But when I console log branchID, It prints my full array, not branchID only.
How can I filter branchID from my Object array. I have no idea what is wrong and why is this happening. If anyone can help me with this, I really appreciate it. Thanks.

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

>Solution :

I think you are misunderstanding what filter function actually does.

You should use the map operator instead to extract a property from your array, like this:

 React.useEffect(()=>{
    setBranchID([...tempTwo.map(item=>item.branchId)])
  },[])
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