簡體   English   中英

Vue.js - 通過另一個 JSON 數組過濾 JSON 數組

[英]Vue.js - Filter array of JSONs by another array of JSONs

我有一個名為products的 JSON 數組和另一個名為deletedProducts的 JSON 數組。

我想過濾那些不在deletedProducts中的產品。

例子:

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

結果應該是這樣的:

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

嘗試過濾和查找方法:

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)

試試這個比較器 function 和過濾器。 (在此示例中由元素“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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM