【问题标题】:Vue.js - Filter array of JSONs by another array of JSONsVue.js - 通过另一个 JSON 数组过滤 JSON 数组
【发布时间】:2020-11-25 16:40:05
【问题描述】:

我有一个名为products 的JSON 数组和另一个名为deletedProducts 的JSON。

我想过滤那些不在deletedProducts中的产品。

例子:

products = [
  {
    id: 1,
    name: 'Box'
  },
  {
    id: 2,
    name: 'Lamp'
  }
]
deletedProducts = [
  {
    id: 1,
    name: 'Box'
  }
]

结果应该是这样的:

result = [
  {
    id: 2,
    name: 'Lamp'
  }
]

【问题讨论】:

    标签: javascript json vue.js vuejs2 vue-component


    【解决方案1】:

    试试这个比较器功能和过滤器。 (本例中元素“id”的数组引用)

     let products = [
      {
        id: 1,
        name: 'Box'
      },
      {
        id: 2,
        name: 'Lamp'
      }
    ]
    
    let deletedProducts = [
      {
        id: 1,
        name: 'Box'
      }
    ]
    
    function comparer(otherArray){
          return function (current) {
              return otherArray.filter(function(other) {
                  return other.id === current.id
              }).length===0;
            }
        }
    
    
    var result=products.filter(comparer(deletedProducts ));
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      尝试过滤和查找方法:

      let result =products.filter(prod=>{
         return !deletedProducts.find(dprod=>{
               return dprod.id===prod.id;
          })
      
      })
      
      

      let products = [{
          id: 1,
          name: 'Box'
        },
        {
          id: 2,
          name: 'Lamp'
        }
      ]
      
      let deletedProducts = [{
        id: 1,
        name: 'Box'
      }]
      
      let result = products.filter(prod => {
        return !deletedProducts.find(dprod => {
          return dprod.id === prod.id;
        })
      
      })
      
      console.log(result)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 2019-12-02
        相关资源
        最近更新 更多