javascript可以在函数调用上实现传递引用技术吗?你看,我下面有JSON
,我需要遍历它的所有节点。遍历时,如果当前项目为Object
且包含密钥nodes
,则必须将另一个属性isParent: true
添加到完全相同的项。但是我在使用这样的功能创建遍历函数时遇到了困难,我尝试搜索遍历函数,但我发现只返回一个新的JSON
对象,而不是更改确切的JSON
正在处理中。
var default_tree = [
{
text: "Applications",
nodes: [
{
text: "Reports Data Entry",
nodes: [
{ text: "Other Banks Remittance Report" },
{ text: "Statement of Payroll Deduction" },
...
]
},
{
text: "Suspense File Maintenance",
nodes: [
{ text: "Banks with Individual Remittances" },
{ text: "Employers / Banks with Employers" },
...
]
}
]
},
{
text: "Unposted Transactions",
nodes: [
{ text: "Unposted Borrower Payments"},
{ text: "Unposted CMP Payments"}
]
},
{ text: "Maintenance" },
{
text: "Reports",
nodes: [
{
text: "Daily Reports",
nodes: [
{
text: "List of Remittance Reports",
nodes: [
{ text: "Banks" },
...
{
text: "Employers-LBP",
nodes: [
{ text: "Employers-Zonal" }
]
},
]
},
...
]
},
...
]
}
]
考虑到我们有这种遍历功能:
function traverse(json_object) {
// perform traversal here
}
traverse(default_tree)
运行遍历函数后,default_tree
的值将保持不变,除非我们执行以下操作:
default_tree = traverse(default_tree)
有人可以帮助我建立一个迭代器的真正的改变Object
进行处理,而迭代,而不是返回一个新的Object
?
答案 0 :(得分:2)
请检查一下
var default_tree = [....] //Array
function traverse(arrDefaultTree){
arrDefaultTree.forEach(function(val,key){
if(val.hasOwnProperty("nodes")){
val.isParent = true;
traverse(val.nodes);
}
})
}
traverse(default_tree);
console.log(default_tree);
希望这有用。
答案 1 :(得分:0)
有两个函数,一个调用然后自我。一个找到节点,另一个循环通过阵列。
traverseTree(default_tree);
function traverseTree (tree) {
var i = 0, len = tree.length;
for(;i < len; i++) {
var obj = tree[i];
findNodes(obj);
}
}
function findNodes (obj) {
var keys = Object.keys(obj);
if (keys.indexOf('nodes') > -1) {
obj.isParent = true;
traverseTree(obj.nodes);
}
}