What i need
- I need to search parent_id with id column in children object.
Json object
{
"key":"1",
"value":{
"id":"150",
"code":"p",
"name":"Parent / Node",
"parent_id":null,
"url":"parent-url",
"children":[
{
"id":"151",
"code":"A",
"name":"A",
"parent_id":"150",
"url":"a-test"
},
{
"id":"152",
"code":"B",
"name":"B",
"parent_id":"150",
"url":"b-test"
},
{
"id":"153",
"code":"Comm",
"name":"Comm",
"parent_id":"150",
"url":"c-test",
"children":[
{
"id":"154",
"code":"c_code",
"name":"comm Code",
"parent_id":"153",
"url":"comm-codes"
},
{
"id":"155",
"code":"forms_c",
"name":"Forms Code",
"parent_id":"153",
"url":"form-cod",
"children":[
{
"id":"156",
"code":"test UME",
"name":"Test Menu",
"parent_id":"155",
"url":"test-menu"
}
]
}
]
}
]
}
}
Js code
console.log(searchNode('153',this.childernNodes));
function searchNode(id, currentNode) {
var i,
currentChild,
result;
//console.log(currentNode);
// if (id == currentNode.parent_id) {
// return currentNode;
// } else {
for (i = 0; i < currentNode.length; i ++) {
currentChild = currentNode[i].node;
result = searchNode(id, currentChild);
return result;
}
}
Input
this.childernNodes object json.
Use case
* Case 1 when user click on menu option i have id and parent_id of clicked item.
* Suppose 153 selected item then i need recreate json according to clicked menu options
Output should be like
* Parent / Node >Comm>Comm Code
- Stack blitz
this.childernNodesin the console log?resultfor you is initialized only as empty variable, and you returning it complete empty.