我有沒有確定的程度JSON樹,它看起來像這樣:刪除對象元素在JavaScript
var nodeset = {
"name" : "FORM",
"attributes" : {
"IDFORM" : "59",
"NOMDOC" : "1",
"VERSFORM" : "1.01",
"DATEREPORT" : "10.10.1988"
},
"nodes" : [{
"name" : "PART1",
"persist" : true,
"nodes" : [{
"name" : "FTYPE",
"persist" : true,
"value" : "1",
"weight" : 1
}, {
"name" : "STARTDATE",
"persist" : true,
"value" : "01.10.2011",
"weight" : 1
}, {
"name" : "ENDDATE",
"persist" : true,
"value" : "31.12.2011",
"weight" : 1
}
],
"value" : "31.12.2011",
"weight" : 3
}, {
"name" : "PART2",
"persist" : true,
"nodes" : [{
"name" : "F203",
"persist" : true,
"value" : 12,
"weight" : 1
}, {
"name" : "F204",
"persist" : true,
"value" : 12,
"weight" : 1
}, {
"name" : "STI059DETAIL",
"persist" : false,
"nodes" : [{
"name" : "F1",
"persist" : false,
"value" : "asd",
"weight" : 1
}, {
"name" : "F2",
"persist" : false,
"value" : "asd",
"weight" : 1
}, {
"name" : "F3",
"persist" : false,
"value" : 0,
"weight" : 0
}, {
"name" : "F4",
"persist" : false,
"value" : 0,
"weight" : 0
}
],
"value" : 0,
"weight" : 2
}, {
"name" : "STI059DETAIL",
"persist" : false,
"nodes" : [{
"name" : "F1",
"persist" : false,
"value" : null,
"weight" : 0
}, {
"name" : "F2",
"persist" : false,
"value" : null,
"weight" : 0
}, {
"name" : "F3",
"persist" : false,
"value" : 0,
"weight" : 0
}, {
"name" : "F4",
"persist" : false,
"value" : 0,
"weight" : 0
}
],
"value" : 0,
"weight" : 0
}, {
"name" : "STI059DETAIL",
"persist" : false,
"nodes" : [{
"name" : "F1",
"persist" : false,
"value" : null,
"weight" : 0
}, {
"name" : "F2",
"persist" : false,
"value" : null,
"weight" : 0
}, {
"name" : "F3",
"persist" : false,
"value" : 0,
"weight" : 0
}, {
"name" : "F4",
"persist" : false,
"value" : 0,
"weight" : 0
}
],
"value" : 0,
"weight" : 0
}
],
"value" : 0,
"weight" : 4
}
],
"weight" : 7
};
我的任務是從中刪除所有節點,其中weight
是0
何nodes
屬性存在。
由於它是一棵樹,我試着使用遞歸函數如下:
function clean(index, owner){
var node = owner[index],
weight = node.weight;
delete node.weight;
if(typeof node.persist != 'undefined'){
delete node.persist;
}
if(!node.nodes)return;
if(!weight){
owner.splice(index, 1);
}
for(var i = 0; i < node.nodes.length; i++){
clean(i, node.nodes);
}
}
for(var i = 0; i < nodeset.nodes.length; i++){
clean(i, nodeset.nodes);
}
但不知何故splice()
,不從那裏刪除任何東西。我用delete owner[index]
取代了它,這會導致null
值在這些節點的位置(我不想在那裏看到:(
)。
我的問題:爲什麼splice()
函數不能像我期望的那樣工作(不會刪除節點)?另外,我採取了正確的做法嗎?如果不是,那麼任何其他建議,將不勝感激。
問候。
測試小提琴HERE,如果它可能有所幫助。
當一個節點權重爲0,在那個節點爲根的整個子樹需要去? –
是的。它需要。只允許'weight' ='0'的'value'節點。整個子樹不是。 – BlitZ