简体   繁体   中英

How to filter objects in a array based on the properties

How can i filter objects in a array based on the objects properties?

I have this code right now:

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

I want to filter the array by the "titel" property of each object. So if the title of the object already exists in the uniqueProducts array it should not add the object.

My code still pushes all three objects to the uniqueProducts array.

Thank you in advaced!

You could filter with a 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM