简体   繁体   English

使用loadsh从数组内的对象中过滤掉唯一值

[英]Filter out unique value from object inside array using loadsh

I am trying to get the unique category from the following array using loadsh, 我试图使用loadsh从以下数组中获取唯一类别,

[{
  "listingId": "p106a904a-b8c6-4d2d-a364-0d21e3505010",
  "section": "section1",
  "category": "VIP PASS ",
  "type": "paper",
  "availableTickets": 1
}, {
  "listingId": "p106904a-b8c6-4d2d-a364-0d21e3505010",
  "section": "section1",
  "category": "VIP PASS ",
  "type": "paper",
  "availableTickets": 2
}, {
  "listingId": "pc8f54389-4e58-482a-9535-6917c2948764",
  "section": "1",
  "category": "WIP",
  "type": "paper",
  "availableTickets": 1
}]

This is what i have tried 这就是我尝试过的

 this.categories = _.uniq(this.listings, function (test: ListDAO) { return test.category; });

but the above returns the same array again. 但是上面再次返回相同的数组。 how can i get the output result as, 我怎样才能得到输出结果,

VIP PASS and WIP VIP PASS和WIP

Without lodash and using .reduce : 如果没有lodash和使用.reduce

let arr2 = arr.reduce((a, i) => a.indexOf(i.category) > -1 ? a : a.concat(i.category), []);

https://jsfiddle.net/42my6p08/ https://jsfiddle.net/42my6p08/

You need to use uniqBy as uniq only accepts a regular array with no callback for each. 你需要使用uniqBy因为uniq只接受一个没有回调的常规数组。

https://lodash.com/docs/4.17.4#uniqBy https://lodash.com/docs/4.17.4#uniqBy

You can try this: 你可以试试这个:

this.categories = _.uniqBy(this.listings, ({ category }) => category);

If you want just the strings (as per comments) you can just do: 如果您只想要字符串(根据评论),您可以这样做:

const getCategory = ({ category }) => category;

this.categories = _.uniqBy(this.listings, getCategory).map(getCategory);

(can also use the same callback function from your OP instead of mine.) (也可以使用OP中的相同回调函数而不是我的。)

A solution using Map and reduce . 使用Mapreduce解决方案。

 var arr = [{ "listingId": "p106a904a-b8c6-4d2d-a364-0d21e3505010", "section": "section1", "category": "VIP PASS ", "type": "paper", "availableTickets": 1 }, { "listingId": "p106904a-b8c6-4d2d-a364-0d21e3505010", "section": "section1", "category": "VIP PASS ", "type": "paper", "availableTickets": 2 }, { "listingId": "pc8f54389-4e58-482a-9535-6917c2948764", "section": "1", "category": "WIP", "type": "paper", "availableTickets": 1 }]; var unique = arr.reduce((map, o) => (map.has(o.category) ? map : map.set(o.category)),new Map()); console.log(Array.from(unique.keys())); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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