从嵌套对象数组中删除重复项,并保留其顺序:javascript [英] Remove duplicate items from array of nested objects and retain their order : javascript
问题描述
我需要在不损害其顺序的情况下从数组中删除重复的项. 请考虑此数据数组
I need to remove the duplicate items from an array without harming their order. Please Consider this array of data
var array = [ { person: { amount: [1,1] } },
{ person: { amount: [1,1] } },
{ person: { amount: [2,1] } },
{ person: { amount: [1,2] } },
{ person: { amount: [1,2] } }];
我知道可以通过使用新的Set([iterable])来完成,但不能与此数组一起使用.如果有人有想法,请帮助.预先感谢.
I understand that it can be done by using new Set([iterable]) but can't work with this array. If anyone have an idea, please help. Thanks in advance.
推荐答案
您可以将元素转换为JSON并将其用作Map的键,然后将其转换回数组(现在由Nina Scholz建议更新) :
You could convert the elements to JSON and use those as keys for a Map, and then convert that back to an array (now with update suggested by Nina Scholz):
var array = [
{ person: { amount: [1,1] } },
{ person: { amount: [1,1] } },
{ person: { amount: [2,1] } },
{ person: { amount: [1,2] } },
{ person: { amount: [1,2] } }
];
var result = [...new Map(array.map( o => [JSON.stringify(o), o])).values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
地图会保留向其中添加项目的顺序,因此原始顺序不会被此过程更改.
A Map maintains the order in which items are added to it, so the original order is not altered by this process.
您也可以使用中间Set而不是Map来执行此操作,但是随后您需要从JSON重构对象,这在您的对象中具有一些与JSON不兼容的非关键属性时会限制功能(例如函数):
You could do it also with an intermediate Set instead of a Map, but then you need to reconstruct the objects from JSON, which limits the functionality when you have some non-key properties in your objects that are not JSON compatible (like functions):
var result = Array.from(new Set(array.map( o => JSON.stringify(o))), s => JSON.parse(s));
这篇关于从嵌套对象数组中删除重复项,并保留其顺序:javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!