简体   繁体   English

Array.filter 不适用于数组,包括对象

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

I have an Array like this.我有一个这样的数组。 在此处输入图像描述

I need branchId only.so I use the filter method to filter this array and store branchId in react state.我只需要branchId。所以我使用过滤器方法来过滤这个数组并将branchId存储在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.但是当我控制台记录 branchID 时,它会打印我的完整数组,而不仅仅是 branchID。 How can I filter branchID from my Object array.如何从我的 Object 数组中过滤 branchID。 I have no idea what is wrong and why is this happening.我不知道出了什么问题,为什么会这样。 If anyone can help me with this, I really appreciate it.如果有人可以帮助我,我真的很感激。 Thanks.谢谢。

I think you are misunderstanding what filter function actually does.我认为您误解了过滤器 function 的实际作用。

You should use the map operator instead to extract a property from your array, like this:您应该使用 map 运算符来从数组中提取属性,如下所示:

 React.useEffect(()=>{
    setBranchID([...tempTwo.map(item=>item.branchId)])
  },[])

Filter is used to filter out all the objects that matches given condition, in your case, the has an id. Filter用于过滤掉与给定条件匹配的所有对象,在您的情况下,具有 id。 To get only the id from list you need to use map要仅从列表中获取 id,您需要使用map

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

Simple way to do that.简单的方法来做到这一点。 You can do this using a map function and your matchId to extract data from the array.您可以使用 map function 和 matchId 从数组中提取数据来执行此操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM