Hello, I have a tree in this form

[ { "name": "InvolvementType", "children": [ { "name": "FULL_TIME", "children": null }, { "name": "PARTIAL", "children": null }, { "name": "EPISODIC", "children": null } ] }, { "name": "IncomeStatus", "children": [ { "name": "BILLABLE", "children": null }, { "name": "NOT_BILLABLE", "children": null } ] }, { "name": "technology", "children": [ { "name": "Android", "children": null }, { "name": "IOS", "children":[ { name: 'Objective C', children: null }, { name: 'Swift', children: null } ] } ] } ] 

I need to select "swift" to understand that this tree elite refers specifically to "technology" and not to "InvolvementType". How to search the tree?

  • and what should I look for? - Grundy
  • it is necessary to find the parent over which there is no parent element anymore. for an element whose name: 'Swift' of the parent is technology, and not IOS - Anna

1 answer 1

It's not entirely clear what you mean.
I made the findByName function, which recursively processes the array, and returns an array of the form ["technology", "IOS", "Swift"] that stores the way it is the parent to the desired element,

 const array = [{ "name": "InvolvementType", "children": [{ "name": "FULL_TIME", "children": null }, { "name": "PARTIAL", "children": null }, { "name": "EPISODIC", "children": null } ] }, { "name": "IncomeStatus", "children": [{ "name": "BILLABLE", "children": null }, { "name": "NOT_BILLABLE", "children": null } ] }, { "name": "technology", "children": [{ "name": "Android", "children": null }, { "name": "IOS", "children": [{ name: 'Objective C', children: null }, { name: 'Swift', children: null } ] } ] } ]; const findByName = (array, name, tail = []) => { for (const obj of array) { if (obj.name === name) { tail.push(obj.name); return tail; } if (obj.children) { const childrenTail = findByName(obj.children, name, [...tail].concat(obj.name)); if (childrenTail.length) return childrenTail; } } return []; } console.log(findByName(array, 'EPISODIC')); console.log(findByName(array, 'Swift')); console.log(findByName(array, '')); 

  • thank you, I have some ideas and I mean - Anna
  • @ Anna, if the problem is solved, accept the answer by clicking on the check mark to the left of it. - Qwertiy
  • @Qwertiy and if there will be more nesting? and for example, some elements will be repeated somewhere, for example, a tree branch with the name "Swift" can beat part of the "technology" branch and some other branch, and you need to understand which branch we took "Swift" - Anna
  • @ Anna, the whole way seems to be displayed here. - Qwertiy
  • @Qwertiy if I add the branch {name: 'Swift', children: null} to the branch {"name": "IncomeStatus", "children": [{"name": "BILLABLE", "children": null}, { "name": "NOT_BILLABLE", "children": null}, {name: 'Swift', children: null}]}, for example, it will only search for the first variant, and how to find the second variant? - Anna