arr.filter去重对象
时间: 2023-11-08 18:00:33 浏览: 39
对于这个问题,可以使用以下代码:
```
const arr = [{id:1,name:'Alice'},{id:2,name:'Bob'},{id:1,name:'Alice'}];
const result = Object.values(arr.reduce((acc,item)=>{
acc[item.id] = item;
return acc;
},{}));
console.log(result);
```
这样就可以将arr数组中的重复对象去除,得到结果:
```
[{id:1,name:'Alice'},{id:2,name:'Bob'}]
```
希望这个回答能帮到你。如果你还有其它问题,可以继续提出。
相关问题
js filter数组对象去重
你可以使用`filter`方法和`indexOf`来过滤数组对象中的重复项。具体步骤如下:
1. 使用`filter`方法迭代数组对象。
2. 在`filter`的回调函数中,使用`indexOf`方法检查当前项在数组中的索引位置。
3. 如果当前项的索引与`indexOf`的返回值相同,则表示当前项是第一次出现,保留该项。
4. 最后返回过滤后的数组。
以下是一个示例代码:
```javascript
let arr = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 1, name: 'Apple' },
{ id: 3, name: 'Orange' }
];
let uniqueArr = arr.filter((item, index) => {
return arr.findIndex(obj => obj.id === item.id) === index;
});
console.log(uniqueArr);
```
输出结果为:
```
[
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
```
这样就实现了对数组对象的去重。希望能对你有所帮助!如果有任何问题,请随时问我。
前端filter对象数组去重
可以使用 Set 数据结构和 Array.from() 方法来实现数组去重。
```javascript
const arr = [{name: 'Alice'}, {name: 'Bob'}, {name: 'Alice'}];
const uniqueArr = Array.from(new Set(arr.map(item => JSON.stringify(item))))
.map(item => JSON.parse(item));
console.log(uniqueArr); // [{name: 'Alice'}, {name: 'Bob'}]
```
上述代码中,先使用 map() 方法将对象数组转换为字符串数组,然后使用 Set 数据结构去重,最后使用 map() 方法将字符串数组转换为对象数组。注意,在将对象转换为字符串时,需要使用 JSON.stringify() 方法,否则无法去重。在将字符串转换为对象时,需要使用 JSON.parse() 方法。