gpt4 book ai didi

javascript - 递归删除具有相同 id 的 JSON 对象

转载 作者:行者123 更新时间:2023-11-28 08:07:33 25 4
gpt4 key购买 nike

我有一个 JSON 列表,其中包含需要删除的重复项,但我找不到方法来执行此操作。

这是我的解决方案。

我想保留使用给定 ID 找到的第一个项目,并删除具有相同 ID 的下一个项目。

问题是,它甚至尝试删除第一个项目。

var gindex = [];

function removeDuplicate(list) {

$.each(list, function(i, val){
console.log(val.id);
console.log(gindex);
if($.inArray(val.id, gindex) == -1) { //in array, so leave this item
gindex.push(val.id);
}
else // found already one with the id, delete it
{
list.splice(i, 1);
}

if(val.children) {
val.children = removeDuplicate(val.children);
}

});

return list;
}

gindex = [];
list = removeDuplicate(parsed_list);
console.log(window.JSON.stringify(list));

最后,这是原始列​​表:

[
{
"id": 0,
"children": [
{
"id": 1,
"children": [
{
"id": 2, // with my algorithm, this one get also flagged for deletion
}
]
},
{
"id": 2, // remove this one
},
{
"id": 3,
},
{
"id": 4, // with my algorithm, this one get also flagged for deletion
"children": [
{
"id": 5, // with my algorithm, this one get also flagged for deletion
"children": [
{
"id": 6, // with my algorithm, this one get also flagged for deletion
}
]
}
]
},
{
"id": 5, // remove this one
"children": [
{
"id": 6, // remove this one
}
]
},
{
"id": 6, // remove this one
},
{
"id": 7,
}
]
}
]

这就是我想要获得的结果

[
{
"id": 0,
"children": [
{
"id": 1,
"children": [
{
"id": 2,
}
]
},
{
"id": 3,
},
{
"id": 4,
"children": [
{
"id": 5,
"children": [
{
"id": 6,
}
]
}
]
},
{
"id": 7,
}
]
}
]

感谢您的回复。

最佳答案

我尝试为此创建自己的逻辑(可能比您想要的更通用),但它可能会帮助您调试代码。请参阅jsFiddle .

核心逻辑是

/**
* Walk through an object or array and remove duplicate elements where the 'id' key is duplicated
* Depends on a seenIds object (using it as a set)
*/
function processData(el) {
// If the element is an array...
if ($.isArray(el)) {
for (var i = 0; i < el.length; i++) {
var value = el[i];
processData(value);

// If the child is now empty, remove it from the array
if (checkForEmpty(value)) {
el.splice(i, 1);
i--; // Fix index after splicing (http://stackoverflow.com/a/9882349/1370556)
}
}
}
// If the element is an object...
else if ($.isPlainObject(el)) {
for (var key in el) {
// Make sure the key is not part of the prototype chain
if (el.hasOwnProperty(key)) {
var value = el[key];

if (key == 'id') {
// If the key has been seen, remove it
if (seenIds[value]) {
delete el[key];
continue; // Skip further processing
} else seenIds[value] = true;
}

processData(value);

// If the child is now empty, remove it from the object
if (checkForEmpty(value)) delete el[key];
}
}
}
}

关于javascript - 递归删除具有相同 id 的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24656845/

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