本文介绍了如何在数组中删除具有相同键和值对的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了许多堆栈溢出问题,但似乎没有人完全回答我的问题。我有一个对象数组,我想通过删除键和值相同的所有对象来减少这些对象。

I've looked through many stack overflow questions, but none seem to quite answer my question. I have an array of objects, which I would like to reduce by deleting all objects where the key and value are the same.

所以我的对象数组是:

[{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]

最终结果应为:

[{a:1},{a:2},{c:3},{b:1},{c:4}]

我尝试过使用filer和map,但我只能获取数组中的第一个对象,而不是所有具有不同键/值对的对象阵列。我也尝试过使用filter和findIndex,但遇到同样的问题。

I've tried using filer and map, but I can only get the first object in the array, rather than all the objects that have different key/value pairs in the array. I've also tried using filter and findIndex, but with the same problem.

在将对象推入数组之前,我也无法过滤对象。

I also can't filter the objects before pushing them into the array.

有人能指出我正确的方向吗?

Can someone point me in the right direction?

推荐答案

你可以比较两个使用(作为Fissure King metions)制作这样的项目的唯一列表:

Alternatively you could use a Set (as Fissure King metions) to make a unique list of items like this:

const array = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]

let unique = [...new Set(array.map(itm => JSON.stringify(itm)))].map(i => JSON.parse(i))

console.log(unique)

这篇关于如何在数组中删除具有相同键和值对的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:40
查看更多