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

Time:12-28

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.

CodePudding user response:

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)])
  },[])

CodePudding user response:

Filter is used to filter out all the objects that matches given condition, in your case, the has an id. To get only the id from list you need to use map

const idList = tempTwo.map(item=> item.branchId)

CodePudding user response:

Simple way to do that. You can do this using a map function and your matchId to extract data from the array.

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(()=>{
    tempTwo.map((branchData, i) => {
      //match your branch id value
      if (branchData.branchId === some_id) {
        setBranchID(branchData.branchId)
      }
    })
  },[])
  • Related