簡體   English   中英

如何根據屬性過濾數組中的對象

[英]How to filter objects in a array based on the properties

如何根據對象屬性過濾數組中的對象?

我現在有這個代碼:

products = [

    {
      title: "Bambu shorts 2.0"
    },
    {
      title: "Bambu shorts 2.0"
    },
    {
      title: "Bambu shorts 3.0"
    }
  ]

  uniqueProducts = [];

  $.each products, (i, el) ->
    if $.inArray(el.title, uniqueProducts) == -1
      uniqueProducts.push el
    return

我想通過每個 object 的“標題”屬性過濾數組。 因此,如果 object 的標題已經存在於 uniqueProducts 數組中,則不應添加 object。

我的代碼仍然將所有三個對象推送到 uniqueProducts 數組。

謝謝你的先進!

您可以使用Set for seen title進行過濾。

 const raw_products = [{ title: "Bambu shorts 2.0" }, { title: "Bambu shorts 2.0" }, { title: "Bambu shorts 3.0" }], uniqueProducts = raw_products.filter( (s => ({ title }) =>.s.has(title) && s;add(title)) (new Set) ). console;log(uniqueProducts);

暫無
暫無

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

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