Getting the parent node of a Json object using jQuery

I am trying to get the parent node in a json object as a Json child that I get from the client - this multi-level directory hierarchy is a hierarchy similar to

Root - -Folder-1 -folder1(a) -folder1(b) -folder-2 -folder-3 -folder3(a) 

what i want when i put folder3(a) id it should give me folder-3 id and name

Here is the fiddle with the actual json object http://jsfiddle.net/jftrg9ko/

+6
source share
1 answer

In any case, you need to search the tree, so just remember the parent and return him if you find the right child.

I mumbled something: http://jsfiddle.net/jftrg9ko/1/

 function getParent(tree, childNode) { var i, res; if (!tree || !tree.folder) { return null; } if( Object.prototype.toString.call(tree.folder) === '[object Array]' ) { for (i in tree.folder) { if (tree.folder[i].id === childNode) { return tree; } res = getParent(tree.folder[i], childNode); if (res) { return res; } } return null; } else { if (tree.folder.id === childNode) { return tree; } return getParent(tree.folder, childNode); } } 
+4
source

Source: https://habr.com/ru/post/974456/


All Articles