I have a parent child tree object. I need to get the level of the child. Appreciate any help. I don't mind to add a property called level to the array.
[
{
"id":"1",
"parent_id":"1",
"children": [
{
"id":"2",
"parent_id":"1",
"children" : [
{
"id":"3",
"parent_id":"2"
},
{
"id":"4",
"parent_id":"2"
}
]
},
{
"id":"5",
"parent_id":"1",
"children" : [
{
"id":"6"
"parent_id":"5"
},
{
"id":"7"
"parent_id":"5"
}
]
}
]
}
]
How about checking the data and creating an array of object with ids, and it's level as property. Something like below:
Edit: Edited to add input field, to make solution fancier/interactive :)
var data = [ { "id": "1", "parent_id": "1", "children": [{ "id": "2", "parent_id": "1", "children": [{ "id": "3", "parent_id": "2" }, { "id": "4", "parent_id": "2" }] }, { "id": "5", "parent_id": "1", "children": [{ "id": "6", "parent_id": "5" }, { "id": "7", "parent_id": "5" }] }] } , { "id": "8", "parent_id": "8" } ]; function findLevel(arr,level) { return arr.reduce(function (levelled, toLevel) { levelled = levelled.concat({"id":toLevel.id,"level":level}); if(toLevel.children) { return levelled.concat(findLevel(toLevel.children,(level+1))); } return levelled; }, []); } var levelledData = findLevel(data,1); console.log(levelledData); //for interactive use only document.getElementById('b').onclick = function() { var elementId = document.getElementById('a').value; var level = levelledData.filter(x => x.id === elementId).map(x => x.level); var message = level.length?"Level of element by id: "+elementId+' is '+level:"Element by id "+elementId+' not found'; alert(message); console.log(message); };
Enter id of children or parent to find level: <input type="text" value="1" id="a"/> <br/> <input type="button" id="b" value="get level"/>
You can find a level of specific node id with the following:
var arrExample = [ { "id": "1", "parent_id": "1", "children": [{ "id": "2", "parent_id": "1", "children": [{ "id": "3", "parent_id": "2" }, { "id": "4", "parent_id": "2" }] }, { "id": "5", "parent_id": "1", "children": [{ "id": "6", "parent_id": "5" }, { "id": "7", "parent_id": "5" }] }] }]; function findLevelHelper(arr, idToFind, level){ if (!arr) { return 0; } for (var i = 0; i < arr.length; i++) { if (arr[i].id === idToFind) { return level; } var foundLevel = findLevelHelper(arr[i].children, idToFind, level + 1); if (foundLevel !== 0) { return foundLevel; } } return 0; } function findLevel(arr, idToFind) { return findLevelHelper(arr, idToFind, 1); } console.log(findLevel(arrExample, "7", 1));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.