I have the following JSON list of objects, and I'm able to find the required object, and pass it back to the caller, given the id
. Everything works fine, I'm just wondering if there's a better (more efficient) way to return the node. I'm open to using a 3rd party tool like lodash
.
JSON payload:
{
"_expanded": true,
"_canDrop": false,
"_id": "-1",
"_name": "root",
"_children": [
{
"_expanded": true,
"_canDrop": false,
"_id": "1",
"_name": "Child 1",
"_children": [
{
"_expanded": true,
"_canDrop": false,
"_id": "1-1",
"_name": "Child 1-1",
"_children": [
{
"_expanded": false,
"_canDrop": false,
"_id": "1-1-1",
"_name": "Child 1-1-1",
"_children": []
}
]
},
{
"_expanded": false,
"_canDrop": false,
"_id": "1-2",
"_name": "Child 1-2",
"_children": []
},
{
"_expanded": false,
"_canDrop": false,
"_id": "1-3",
"_name": "Child 1-3",
"_children": []
}
]
},
{
"_expanded": true,
"_canDrop": false,
"_id": "2",
"_name": "Child 2",
"_children": [
{
"_expanded": false,
"_canDrop": false,
"_id": "2-2",
"_name": "Child 2-2",
"_children": []
}
]
}
]
}
Find method:
public findNode = (id: any): TreeNode => {
let result = null;
if (this._id === id) {
result = this;
} else {
if (this._children.length > 0) {
for (let index = 0; index <= this._children.length - 1; index++) {
result = this._children[index].findNode(id);
if (result) {
break;
}
}
}
}
return result;
}