【问题标题】:Javascript object filteringJavascript对象过滤
【发布时间】:2020-12-04 22:21:57
【问题描述】:

我有一个产品列表作为对象数组,类似于

[ {
   id: 1,
   price: 10,
   name: 'product',
   categories: [
                 {id: 1, name: 'category 1'} ]
   }, 
{
   id: 2,
   price: 10,
   name: 'product3',
   categories: [
                 {id: 1, name: 'category 1'},
                  {id: 2, name: 'category 2'},]
   }, 
... 
]

等等。

我正在尝试根据类别 id 过滤产品,这是最好的(也是最现代的)方法?而且由于我正在使用 Node.js,是否可以更好地处理“副本” 的数据,以便我始终保持完整的数据集完整用于其他用途? (如另一个过滤,或过滤器删除)

【问题讨论】:

  • theArray.filter(product => product.categories.find(category => category.id === desiredId))

标签: javascript arrays object filter


【解决方案1】:

我会使用filter 对每个对象应用条件。在这种情况下,我会在categories 上使用some,以便找到至少有一个类别符合条件的产品:

const searchCategory = 1; // Just an exmaple
const result = products.filter(p => p.categories.some(c => c.id === searchCategory));

【讨论】:

    【解决方案2】:

    我会使用.filter(),在回调中,我会使用.some() 来检查是否有任何类别具有正确的ID。如果你只需要一个,你可以用.find()代替.filter()

    由于您正在使用对象引用,因此您必须小心,因为过滤后的数组中的对象指向与原始数组相同的对象。也就是说,如果修改了过滤后数组的第一个元素,原数组就会更新。

    关于您是否需要保留完整数据集的问题,您的表述方式过于宽泛,无法正确回答。您显然应该将所有数据保存在某个地方,但是在哪个级别使用过滤数组以及在哪个级别使用完整数组取决于您的架构决策。

    【讨论】:

      【解决方案3】:

      使用Array.filter()

      const arr = [ {
         id: 1,
         price: 10,
         name: 'product',
         categories: [
                       {id: 1, name: 'category 1'} ]
         }, 
      {
         id: 2,
         price: 10,
         name: 'product3',
         categories: [
                       {id: 1, name: 'category 1'},
                        {id: 2, name: 'category 2'},]
         }
      ]
      
      arr.filter(_o => _o.categories.filter(_c => _c.id === 2).length) // Change the "2" to whatereve you like to match the category ID
      

      【讨论】:

        猜你喜欢
        • 2020-05-29
        • 2015-09-28
        • 1970-01-01
        • 2021-04-11
        • 2012-11-15
        • 2021-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多