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/