如何在数组中删除具有相同键和值对的对象 [英] How to remove objects with the same key and value pair in arrays

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

问题描述

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

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?

推荐答案

你可以比较两个使用 JSON.stringify()。然后,我们使用 reduce <添加到新阵列/ a>,如果它在数组中我们不添加它,否则我们会添加它。

You can compare the two items using JSON.stringify(). We then add to a new array using reduce, if it is in the array we don't add it otherwise we do add it.

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

let unique = array.reduce((res, itm) => {
  // Test if the item is already in the new array
  let result = res.find(item => JSON.stringify(item) == JSON.stringify(itm))
  // If not lets add it
  if(!result) return res.concat(itm)
  // If it is just return what we already have
  return res
}, [])

console.log(unique)

或者你可以使用设置(作为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)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆