簡體   English   中英

array.filter 不返回 reactjs 中父數組的嵌套數組

[英]array.filter not returning nested array of parent array in reactjs

我有一個嵌套數組。 我正在使用array.filter從父數組中獲取子數組。

我有這樣的數據:

"accounts": [
    {

        "ID": "001yQdmAAE",
        "email": "inhome.user@ator.com",
        "users": [
            {
                "Name": "Inhome User",                    
                "MobilePhone": "34877"
            }
        ]
    },
    {
        "ID": "00mAAE",
        "email": "in.user@ator.com",
        "users": [
            {
                "Name": "Inhome r",                    
                "MobilePhone": "300077"
            }
        ]
   }]

我想根據 ID 從帳戶數組中獲取用戶數組。 我試過array.filter 它返回

    { "ID": "001yQdmAAE",
      "email": "inhome.user@ator.com",
      "users": [
        {
           "Name": "Inhome User",                    
           "MobilePhone": "34877"
        }
    }

我只想要用戶數組

const res=this.state.data.filter((res)=>{
 if(res.ID==record.ID){
       return res.users;
 }
});
console.log(res);

這不是filter的工作原理。 filter的回調 function 應該返回一個 boolean 結果,該結果確定傳遞給回調的元素是否應該包含在filter的返回值中。 執行過濾后,我們將map每個結果 object 提取其users屬性。

 const /*this.state.*/data = {"accounts": [{"ID": "001yQdmAAE","email": "inhome.user@ator.com","users": [{"Name": "Inhome User","MobilePhone": "34877"}]},{"ID": "00mAAE","email": "in.user@ator.com","users": [{"Name": "Inhome r","MobilePhone": "300077"}]}]}; const targetID = "00mAAE"; const result = data.accounts.filter(e => e.ID === targetID).map(e => e.users); console.log(result);

但如果ID是唯一的,則使用find而不是filter ,它只定位第一個匹配項:

 const data = {"accounts": [{"ID": "001yQdmAAE","email": "inhome.user@ator.com","users": [{"Name": "Inhome User","MobilePhone": "34877"}]},{"ID": "00mAAE","email": "in.user@ator.com","users": [{"Name": "Inhome r","MobilePhone": "300077"}]}]}; const targetID = "00mAAE"; const result = data.accounts.find(e => e.ID === targetID); if (result) { console.log(result.users); }

您還需要使用map來返回正確的數據部分:

const res = this.state.data.filter(res => res.ID === record.ID).map(item = > item.users); // Add map here to get users array

過濾器返回 true 或 false,如果返回 false,則過濾掉該元素。

您應該首先過濾返回 true 或 false,然后使用 map 僅獲取用戶,然后使用 flat 將二維數組轉換為普通數組。

const res=this.state.data.filter(
  res=>
    //return true or false in filter
    res.AccountID==record.AccountID
).map(
  //only need the users property
  res=>res.users
).flat();//flatten [users] to users
console.log(res);

 var data = {"accounts": [ { "ID": "001yQdmAAE", "email": "inhome.user@ator.com", "users": [ { "Name": "Inhome User", "MobilePhone": "34877" } ] }, { "ID": "00mAAE", "email": "in.user@ator.com", "users": [ { "Name": "Inhome r", "MobilePhone": "300077" } ] }] } function getUsers(){ var xx; data.accounts.forEach(x => { if(x.ID == "00mAAE"){ xx = x.users; } }) return xx; }; console.log(getUsers());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM