使用 JavaScript 進行巢狀集合篩選


假設我們有一個這樣的巢狀物件陣列−

const arr = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 2,
   legs:[{
      carrierName: 'SunExpress'
   },
   {
      carrierName: 'SunExpress'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];

我們需要編寫一個 JavaScript 函式,該函式將一個這樣的陣列作為第一個引數,並將一個搜尋查詢字串作為第二個引數。

我們的函式應過濾該陣列,僅包含其“運營商名稱”屬性值與第二個引數指定的值相同的物件。

如果對於上述陣列,第二個引數為“天馬”。那麼輸出應該如下所示 −

const output = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];

示例

程式碼如下 −

const arr = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 2,
   legs:[{
      carrierName: 'SunExpress'
   },
   {
      carrierName: 'SunExpress'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];
const keys = ['Pegasus'];
const filterByKeys = (arr = [], keys = []) => {
   const res = arr.filter(function(item) {
      const thisObj = this;
      return item.legs.some(leg => {
         return thisObj[leg.carrierName];
      });
   }, keys.reduce((acc, val) => {
      acc[val] = true;
      return acc;
   }, Object.create(null)));
   return res;
}
console.log(JSON.stringify(filterByKeys(arr, keys), undefined, 4));

輸出

控制檯中的輸出將如下所示 −

[
   {
      "id": 1,
      "legs": [
         {
            "carrierName": "Pegasus"
         }
      ]
   },
   {
      "id": 3,
      "legs": [
         {
            "carrierName": "Pegasus"
         },
         {
            "carrierName": "SunExpress"
         }
      ]
   }
]

更新日期: 2020 年 11 月 24 日

996 次瀏覽

開啟 職業發展

完成課程取得認證

開始
廣告