gpt4 book ai didi

javascript - 从 Javascript/Typescript 数组中删除子对象重复项

转载 作者:行者123 更新时间:2023-12-02 22:47:22 25 4
gpt4 key购买 nike

我有一个充满对象的数组。几乎所有对象都有不同数量的键值对。其中一些对象具有相同的键值对。

有没有一个好的方法来删除所有子对象重复项? (sub-object-duplicate = 其所有键值对都可以在另一个对象中找到的对象。)

在下面的示例中,例如它将删除所有中间对象,只留下第一个和最后一个。

非常感谢:)

我得到的最接近的是使用 here 中的这个,但我不知道如何添加 if 条件以仅检查属性是否存在。

具有多个唯一属性(id 和 name)

arr.filter((v,i,a)=>a.findIndex(t=>(t.id === v.id && t.name===v.name))===i)

输入

input = [
{
"key0": {
"key1": "value1",
"key2": "value1",
"key3": "value1",
"key4": "value1",
"key5": "value1"
}
},
{
"key0": {
"key1": "value1",
"key3": "value1",
"key5": "value1"
}
},
{
"key0": {
"key1": "value1",
"key2": "value1",
"key3": "value1"
}
},
{
"key0": {
"key1": "value1",
"key2": "value1",
"key5": "value1"
}
},
{
"key0": {
"key1": "value1",
"key2": "value2",
"key3": "value2",
"key4": "value2",
"key5": "value2",
"key6": "value2"
},
{
"key0": {
"key1": "value2",
"key2": "value2",
"key3": "value2",
"key4": "value2",
"key5": "value2",
"key6": "value2"
}
}
]

预期输出

output = [
{
"key0": {
"key1": "value1",
"key2": "value1",
"key3": "value1",
"key4": "value1",
"key5": "value1"
}
},
{
"key0": {
"key1": "value2",
"key2": "value2",
"key3": "value2",
"key4": "value2",
"key5": "value2",
"key6": "value2",
}
}
]

最佳答案

这是一个非常基本的 O(n2) 复杂解决方案:

var input = [
{
"key0": {
"key1": "value1",
"key2": "value1",
"key3": "value1",
"key4": "value1",
"key5": "value1"
}
},
{
"key0": {
"key1": "value1",
"key3": "value1",
"key5": "value1"
}
},
{
"key0": {
"key1": "value1",
"key2": "value1",
"key3": "value1"
}
},
{
"key0": {
"key1": "value1",
"key2": "value1",
"key5": "value1"
}
},
{
"key0": {
"key1": "value1",
"key2": "value2",
"key3": "value2",
"key4": "value2",
"key5": "value2",
"key6": "value2"
}
},
{
"key0": {
"key1": "value2",
"key2": "value2",
"key3": "value2",
"key4": "value2",
"key5": "value2",
"key6": "value2"
}
}
];

var isIncluded = function (a, b) {
for (var key in a) {
if (!b[key] || b[key] !== a[key])
return false;
}

return true;
};


var output = [];

for (var i = 0; i < input.length; i++) {
var toInclude = true;

for (var j = 0; j < input.length; j++) {
if (j === i)
continue;

if (isIncluded(input[i].key0, input[j].key0)) {
toInclude = false;
break;
}
}

if (!toInclude)
continue;

output.push(input[i]);
}

console.log(output);
// document.write(JSON.stringify(output));

请注意,输出得到 3 个项目,因为您可能在其中一个对象中犯了错误(混合了 value1 和 value2)

关于javascript - 从 Javascript/Typescript 数组中删除子对象重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58341182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com