我有像这样的jsonarray
var MAinobj =
{
{
Name:"iteration1",
Parent:null
},
{
Name:"iteration2",
Parent:null
},
{
Name:"iteration3",
Parent:"null"
},
{
Name:"step2",
Parent:"iteration1"
},
{
Name:"step3",
Parent:"iteration2"
},
{
Name:"step4",
Parent:"iteraton3"
},
{
Name:"task1",
Parent:"step3"
},
{
Name:"task2",
Parent:"step3"
},
}
我想要的是我的json数组看起来像这样。我会给出像iteration2这样的名字,然后我需要删除它的所有子节点和子节点也意味着在删除我的json对象后看起来像这样:
var Mainobj =
{
{
Name:"iteration1",
Parent:null
},
{
Name:"iteration3",
Parent:null
},
{
Name:"step2",
Parent:"iteration1"
},
{
Name:"step4",
Parent:"iteration3"
}
}
我希望我的json对象看起来像这样
答案 0 :(得分:0)
首先,json数组由[]而非{}包围。如果你想要一个对象,你应该为每个元素命名,如下所示:
var mainObj = {
"step2": {...},
"step3": {...}
}
您可能需要查看recursion。您可以创建一个函数来搜索数组中具有特定父级的所有元素。在删除每个元素之前,调用该函数,传递找到的子元素。
这样的事情:
function removeTree(list, parentName){
var index = 0;
while (index < list.length){ // The list length will change with each element removed
var elem = list[index];
if (elem.Name === parentName){ // "parent" found
list.splice(index,1); // Remove the current element
} else if (elem.Parent === parentName) { // "child" found
list.splice(index,1); // Remove the current element
removeTree(list, elem.Name); // Remove all its children
} else {
index++; // If this element isn't a child of parentName, look at the next one
}
}
};