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

时间:2017-07-17 18:18:11

标签: javascript arrays typescript

我正在尝试使用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.categories = _.uniq(this.listings, function (test: ListDAO) { return test.category; });

但上面再次返回相同的数组。我怎样才能得到输出结果,

VIP PASS和WIP

3 个答案:

答案 0 :(得分:4)

没有lodash并使用.reduce

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

https://jsfiddle.net/42my6p08/

答案 1 :(得分:3)

您需要使用uniqBy,因为uniq只接受一个没有回调的常规数组。

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

你可以试试这个:

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

如果您只想要字符串(根据评论),您可以这样做:

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

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

(也可以使用OP中的相同回调函数而不是我的。)

答案 2 :(得分:0)

使用 private class YamlDocumentFilter : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { string file = AppDomain.CurrentDomain.BaseDirectory + "swagger_yaml.txt"; if (!File.Exists(file)) { var serializer = new YamlSerializer(); serializer.SerializeToFile(file, swaggerDoc); } } } private class YamlDocumentFilter : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { string file = AppDomain.CurrentDomain.BaseDirectory + "swagger.yaml"; if (!File.Exists(file)) { var serializer = new YamlDotNet.Serialization.Serializer(); using (var writer = new StringWriter()) { serializer.Serialize(writer, swaggerDoc); var stream = new StreamWriter(file); stream.WriteLine(writer.ToString()); } } } } 的解决方案。

Map