如何获取JavaScript数组中一组对象的唯一属性

Suppose you have a bills array with this content:

假设您有一个具有以下内容的bills数组:

const bills = [
  { date: '2018-01-20', amount: '220', category: 'Electricity' },
  { date: '2018-01-20', amount: '20', category: 'Gas' },
  { date: '2018-02-20', amount: '120', category: 'Electricity' }
]

and you want to extract the unique values of the category attribute of each item in the array.

并且您要提取数组中每个项目的category属性的唯一值。

Here’s what you can do:

您可以执行以下操作:

const categories = [...new Set(bills.map(bill => bill.category))]

说明 (Explanation)

Set is a new data structure that JavaScript got in ES6. It’s a collection of unique values. We put into that the list of property values we get from using map(), which how we used it will return this array:

Set是JavaScript在ES6中获得的新数据结构。 它是唯一值的集合。 我们将使用map()获得的属性值列表放入其中,使用它的方式将返回此数组:

['Electricity', 'Gas', 'Electricity']

Passing through Set, we’ll remove the duplicates.

通过Set,我们将删除重复项。

... is the spread operator, which will expand the set values into an array.

...散布运算符 ,它将把设置值扩展为一个数组。

翻译自: https://flaviocopes.com/how-to-get-unique-properties-of-object-in-array/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值