2015-10-16 39 views
0

刪除元素我有這樣從Hierarichal對象的jQuery

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" 
}, 
} 

我想jsonarray是我的JSON數組這個樣子。我會給像迭代2的名稱,然後我需要刪除其所有的兒童和subchildrens也刪除我的JSON對象是這樣的裝置之後:

var Mainobj = 
{ 
{ 
Name:"iteration1", 
Parent:null 
}, 
{ 
Name:"iteration3", 
Parent:null 
}, 
{ 
Name:"step2", 
Parent:"iteration1" 
}, 
{ 
Name:"step4", 
Parent:"iteration3" 
} 
} 

我希望我的JSON對象看起來像這樣

+0

歡迎堆棧溢出!你似乎在要求某人爲你寫一些代碼。堆棧溢出是一個問答網站,而不是代碼寫入服務。請[see here](http://stackoverflow.com/help/how-to-ask)學習如何編寫有效的問題。 –

回答

0

首先,JSON數組被[] not {}封裝。如果你想要一個對象,而不是,你應該給一個名稱,每個元素,像這樣:

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 
     } 
    } 
};