在嵌套对象内高效查找和过滤

问题描述 投票:0回答:1

使用 Vue3 我有以下对象 $products

[{ 
   "id": 1, 
   "item": "Product 1", 
   "productcategories": [{ 
      "id": 300, 
      "title": "Category300" 
   },
   { 
      "id": 301, 
      "title": "Category301" 
   }], 
},
{ 
   "id": 2, 
   "item": "Product 2", 
   "productcategories": [{ 
      "id": 200, 
      "title": "Category200" 
   }], 
},
{ 
   "id": 3, 
   "item": "Product 3", 
   "productcategories": [{ 
      "id": 301, 
      "title": "Category301" 
   },
   { 
      "id": 309, 
      "title": "Category309" 
   }], 
}]

请注意:

//object type
console.log(typeof products.value);

//returns '300'
console.log(products.value[0]["productcategories"][0]["id"]);

请注意,每个产品可以有多个产品类别。

我想过滤这个对象并获取一个包含那些产品的对象,其中至少一个产品类别 ID 为 301。理想的结果 $filtered_products 是:

[{ 
   "id": 1, 
   "department_id": 2, 
   "item": "Product 1", 
   "productcategories": [{ 
      "id": 300, 
      "title": "Category300" 
   },
   { 
      "id": **301**, 
      "title": "Category301" 
   }], 
},
{ 
   "id": 3, 
   "department_id": 2, 
   "item": "Product 1", 
   "productcategories": [{ 
      "id": **301**, 
      "title": "Category301" 
   },
   { 
      "id": 309, 
      "title": "Category309" 
   }], 
}]

我愿意接受任何建议,我的目标是使搜索尽可能高效。

javascript vue.js performance sorting filter
1个回答
0
投票

借助 Array.prototype.some:

function hasProductsWithCategory(category) {
  return data.filter(
    ({ productcategories }) => 
      productcategories.some(({ id }) => id === category
    )
  );
}

查看结果:

const data = [{
    "id": 1,
    "item": "Product 1",
    "productcategories": [{
        "id": 300,
        "title": "Category300"
      },
      {
        "id": 301,
        "title": "Category301"
      }
    ],
  },
  {
    "id": 2,
    "item": "Product 2",
    "productcategories": [{
      "id": 200,
      "title": "Category200"
    }],
  },
  {
    "id": 3,
    "item": "Product 3",
    "productcategories": [{
        "id": 301,
        "title": "Category301"
      },
      {
        "id": 309,
        "title": "Category309"
      }
    ],
  }
]

function hasProductsWithCategory(category) {
  return data.filter(({
    productcategories
  }) => productcategories.some(({
    id
  }) => id === category))
}

const filtered = hasProductsWithCategory(301);

console.log(filtered);

© www.soinside.com 2019 - 2024. All rights reserved.