【发布时间】:2014-08-30 15:58:37
【问题描述】:
我有一个 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,
}
]
}
]
感谢您的回复。
【问题讨论】:
-
您当前的解决方案有什么问题?
-
未捕获的类型错误:无法读取未定义的属性“id”。
-
问题一定出在你的算法中,因为重复的 2、4 和 5 正在被删除......如果你想删除前 4 和 5,你必须在别处做错事
-
我想保留给定 ID 找到的第一个项目,并删除具有相同 ID 的下一个项目
-
我假设 $.each 不喜欢在迭代数组时对其进行变异。考虑改为创建一个新数组。
标签: javascript jquery json recursion