javascript - 如何通过新集合从对象中获取唯一数组?
问题描述
如何通过新集合从对象中获取唯一数组?
我有一个包含对象的数组,我怎样才能获得一个唯一的数组,但只能保留 id?
IE:[{id: 1, title: 'test1'}, {id: 2, title: 'test2'}]
const arr = [{id: 1, title: 'test1'}, {id: 2, title: 'test2'}, {id: 1: title: 'test1'}]
const filtered = arr.filter((item) => item.title)
const result = Array.from(new set(arr))
解决方案
您可以获取一个哈希表并获取它的值。
这种方法将最后找到的对象与相同的id
.
const
array = [{ id: 1, title: 'first' }, { id: 2, title: 'test2' }, { id: 1, title: 'last' }],
unique = Object.values(array.reduce((r, o) => (r[o.id] = o, r), {}));
console.log(unique);
通过使用Set
带有闭包的 a,您可以过滤数组。
这种方法采用与第一个找到的对象相同的id
.
const
array = [{ id: 1, title: 'first' }, { id: 2, title: 'test2' }, { id: 1, title: 'last' }],
unique = array.filter((s => ({ id }) => !s.has(id) && s.add(id))(new Set));
console.log(unique);
推荐阅读
- javascript - `Object` 是 JavaScript 中的函数吗?
- c - 指向引用函数的指针数组的指针,如何更改指针值和调用函数?
- php - FCM 推送通知问题:- 不显示三星手机等通知图像
- sql - SQL 分组依据。为所有组添加具有平均结果的新行
- javascript - 预订应用程序调用函数
- python - 使用 BeautifulSoup 在 python 中抓取多个页面
- php - 如何在php url中的标题后显示id
- parameters - 在运行时更改 ODM 规则服务器中的规则参数?
- android-studio - android studio:插件flutter-i18n不起作用
- python - 调查结果的条形图为 pd.value_counts()