使用 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 次浏览

开启 职业发展

完成课程取得认证

开始
广告
© . All rights reserved.