簡體   English   中英

如何過濾對象數組的 arrays 數組?

[英]How to filter array of arrays of array of objects?

我正在嘗試過濾 arrays 個對象的數組,但它不起作用。

   constructNewGrid(filterText){
      if(searchText == ""){
        this.constructedGrid = this.fullGrid;
        return;
      }
      this.constructedGrid = [];
      this.constructedGrid = this.fullGrid.filter(array => array.filter(obj => {
        if(obj.name == filterText)
          return obj;
      }));
      console.log(this.constructedGrid);
   }

我想返回一個 arrays 的數組,如果找到一個正確的 object,但是當我控制台記錄它時, constructedGrid是同一個數組,但為什么呢? 代碼應該 go 到第一個數組應該查找是否有名稱等於過濾器文本的 object 它應該返回具有相應 object 的數組,然后應該檢查下一個數組等等。

這將是格式:

[ 
  [[{name: string}], empty, empty], // array of lenth 3 
  [empty, empty, [{name: string}], empty], // array of length 4 
   ... 
]

如果找到一個 object,它應該將它分別放入一個數組中,這樣如果在同一個數組中找到兩個對象,它應該將它們分別放入兩個單獨的 arrays 中,並且它們應該在一個數組中:結果應該是

[
 [[obj1]],
 [[obj2]],
 ...
]

這對我來說似乎是可能的。 有時我得到一個錯誤,我沒有 memory 哈哈......

除了filter之外,您還需要map ,因為filter只是決定是否保留那里的內容,它不會改變那里的內容。 map可以。 是這樣的:

  this.constructedGrid = this.fullGrid
      // Map the inner array to one that only has matching entries
      .map(array => array.filter(obj => obj && obj.name === filterText))
      // Remove blank inner arrays from the overall array
      .filter(array => array.length);

現場示例:

 const fullGrid = [ [[{name: "target"}], , ], [, null, [{name: "target"}], undefined], ]; const filterText = "target"; const constructedGrid = fullGrid // Map the inner array to one that only has matching entries.map(array => array.filter(obj => obj && obj[0] && obj[0].name === filterText)) // Remove blank inner arrays from the overall array.filter(array => array.length); console.log(constructedGrid);
 .as-console-wrapper { max-height: 100%;important; }

請注意,如果要從外部數組中刪除完全為空的 arrays,則只需要第二個filter 如果您想離開他們,只需刪除該電話即可。 編輯:從你對我關於這個問題的問題的回復來看,聽起來你想刪除第二個.filter

注意第一個filter中的守衛,即obj && obj[0] &&部分。 它在那里是因為你說有時數組條目是“空的”。 我不知道您的字面意思是空的(稀疏數組)還是undefined的條目。 如果你的字面意思是的(一個稀疏數組),你不需要守衛,但最好有它。

從 ES2020 開始,您可以改用可選的鏈接運算符:

.filter(obj => obj?.[0]?.name === filterText)

如果objnullundefined ,或者obj[0]nullundefinedobj?.[0]?.name計算結果為undefined 否則它的計算結果為obj[0].name 由於undefined === filterText將為 false,帶有nullundefined obj的條目將被排除在外。 不過,同樣是新功能,如果您不進行轉譯,則需要檢查目標瀏覽器的支持情況。

暫無
暫無

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

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